Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test private methods and internal classes with NUnit?

How do I test private methods and internal classes using NUnit?

like image 895
SNA Avatar asked Jun 10 '09 03:06

SNA


People also ask

Can you test private methods in C#?

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.

How do you test a method in NUnit?

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.

Can we unit test private methods?

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.

What is difference between NUnit and MsTest?

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.


2 Answers

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.

like image 76
Joe White Avatar answered Sep 20 '22 17:09

Joe White


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.

like image 41
Bill the Lizard Avatar answered Sep 20 '22 17:09

Bill the Lizard