Testing private methods with NUnit Framework and C#
In this article on NUnit, I am going to write some unit tests for all the private methods in my custom class. I have decided to write this article because in one of my project, we had an object responsible for talking to a third party vendor. In that object, there was a private method which was doing a lot of heavy lifting work such as making sure all the required parameters are supplied to talk to the vendor, ensuring that communication must take place via Https instead of Http and finally returning a unsigned 32 bit integer from the third party vendor.
Note : I am making assumption that readers of this articles are developers who do write UNIT test for all their public methods and not going to go over the procedure of creating NUNIT Project.
First of all, I am going to create a Unit Test class named “PrivateMethodTester” and provide all the needed attributes to my class and methods. After that I will create my custom class that will have all the private methods. Some of these methods will be static and others will be non-static. The reason for creating both static and non-static methods within this class is to show the slight different ways of testing them.
I include all the required namespaces to my Unit Test class especially the System.Reflection namespace. This is the namespace that is responsible for calling all the private methods of the custom object at runtime using its different classes such as MethodInfo etc.
Let us start testing with a non-static, not parameterized private method such as “GetValue() “of the class shown below. This class is very simple; it just returns a string once it is invoked. Please expand the plus image to see the class to be tested. Pay especial attention to the private method named “GetValue()”.
Now let us look at the UNitTest class at which this method is tested. Click at the image below to see all the codes.