Reputation: 7728
How do I test private methods and internal classes using NUnit?
Upvotes: 12
Views: 13618
Reputation: 1061
Just use the solution shown here: C# "internal" access modifier when doing unit testing
and you will see that internals can and should be tested.
Upvotes: 1
Reputation: 1899
The way I handle this is that I make all my methods public. I know that sounds bad, but bear with me a moment.
When using IoC you have an interface for every class that has some logic in it. So basically you code against the interface, and not the actual implementation. What this let's you do is to mark all of the methods public and it does't affect the way that the class is used, except it makes it possible to write unit tests for every method in that class.
Upvotes: 2
Reputation: 97818
Private methods:
If you're trying to test non-public methods, it usually means you're doing it wrong.
If there's functionality that you want to test, but don't want to make public on your class, the code is trying to tell you something. Your class probably has too many responsibilities. You should seriously consider extracting that private functionality into a new class, writing tests for the new class, and making your old class have a private instance of the new class.
Internal classes:
This one is more valid, especially if you're writing a class library for others to reuse. You may have classes that aren't designed for general use, but that you want to write unit tests for.
For this case, take a look at InternalsVisibleToAttribute.
Upvotes: 32
Reputation: 405995
I typically don't. If you thoroughly test the public methods that use private methods and internal classes then you should be able to test the full range of the private functionality without exposing it.
Upvotes: 5
Reputation: 39510
You have to expose a means to invoke them, possibly through a test-specific derived class.
Upvotes: 0