How do I test private methods and internal classes using NUnit?
Private methods exist due to code reusability and to avoid having large public methods that do everything. 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.
To mark a method as a test case, we need to add a Test attribute. It tells the NUnit framework that it should run this method. It's a good approach to run our test methods with different arguments, without copy-pasting our test methods. We can define test method parameters by using the [TestCase] attribute.
Why We Shouldn't Test Private Methods. As a rule, the unit tests we write should only check our public methods contracts. Private methods are implementation details that the callers of our public methods aren't aware of. Furthermore, changing our implementation details shouldn't lead us to change our tests.
MsTest is a native unit testing library that comes with Visual Studio from Microsoft. NUnit is an extra Nuget package that needs to be installed on top and interact with the APIs of Visual Studio. Nunit likely doesn't have direct integration into the native APIs like MsTest does.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With