Unit testing for private methods in asp.net c#

Unit testing is very important part of Software/Web development. Basically its a testable part of the application in which you can write unit test cases for each and every public classes and methods. Writing unit test cases means making sure that all part of the functionality development are working fine without any break. You can also do unit testing for private methods.

If you do not know about unit testing, you can see MSDN walk-through of creating and running test cases here

Now I have seen few developers raising question that they do not able to write unit test cases for private methods. In general there is no need to write unit test cases for private method. Because unit test cases for public method which consumes these private methods covers private method. For Example I have a public method which consumes private method as shown below:

Now if you write unit test cases for public method named ‘PublicMethod’ here as shown below, it will automatically covers private method. have a look at below code:

So as shown in above code when you execute test method, MethodA will internally call MethodB. So no need to write extra test cases for MethodB. 🙂

But, In some cases situation comes that you want to do unit testing for private method by hook or by crook. Here there is a good news for you that you can do unit testing for private methods as well. 🙂

Considering above example of Class1 , I have created unit testing for private method as shown below:

As you can see in above code snippet, I have used PrivateObject  which creates wrapper of ClassA() and Invoke method will help to access the member of the ClassA. As you can see in below image that accessor.Invoke(“MethodB”) returned me a result of private method MethodB.


Now what if your private method accepts input parameters as shown below:

So in that case you have to provide parameter values in Invoke() method of PrivateObject as shown below:

Hope you have enjoyed this post. Have a great day 🙂