Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test private methods with NUnit?

I am wondering how to use NUnit correctly. First, I created a separate test project that uses my main project as reference. But in that case, I am not able to test private methods. My guess was that I need to include my test code into my main code?! - That doesn't seem to be the correct way to do it. (I dislike the idea of shipping code with tests in it.)

How do you test private methods with NUnit?

like image 885
MrFox Avatar asked Oct 30 '08 11:10

MrFox


People also ask

Can we write test cases for private methods in NUnit?

You don't test private functions. There are ways to use reflection to get into private methods and properties. But that isn't really easy and I strongly discourage this practice. You simply shouldn't test anything that's not public.

Can you test private methods in C#?

By testing private methods, your tests will become more fragile because and you'll tend to break them every time you change code in and around those private methods. On the other hand, by testing public methods only, you'll reduce the number of unit tests you need, and you'll make tests less brittle.

How do you test private methods?

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.


2 Answers

Generally, unit testing addresses a class's public interface, on the theory that the implementation is immaterial, so long as the results are correct from the client's point of view.

So, NUnit does not provide any mechanism for testing non-public members.

like image 91
harpo Avatar answered Oct 17 '22 04:10

harpo


While I agree that the focus of unit testing should be the public interface, you get a far more granular impression of your code if you test private methods as well. The MS testing framework allows for this through the use of PrivateObject and PrivateType, NUnit does not. What I do instead is:

private MethodInfo GetMethod(string methodName) {     if (string.IsNullOrWhiteSpace(methodName))         Assert.Fail("methodName cannot be null or whitespace");      var method = this.objectUnderTest.GetType()         .GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);      if (method == null)         Assert.Fail(string.Format("{0} method not found", methodName));      return method; } 

This way means you don't have to compromise encapsulation in favour of testability. Bear in mind you'll need to modify your BindingFlags if you want to test private static methods. The above example is just for instance methods.

like image 30
user1039513 Avatar answered Oct 17 '22 04:10

user1039513