HI WELCOME TO SIRIS

Unit Test private method in C# .NET

Leave a Comment


This is a very common c# interview question. As a developer all of us know, how to unit test public members of a class. All you do is create an instance of the respective
class and invoke the methods using the created instance. So, unit testing public methods is very straight forward, but if the method that we want to unit test is a private method, then we cannot access it outside the class and hence cannot easily unit test it. 


Consider the example class shown below. CalculatePower() method with in the Maths class is private and we want to unit test this method. Also, note that CalculatePower() is an instance private method. In another articel we will discuss the concept of unit testing a private static method. Microsoft's unit testing assembly contains a class called PrivateObject, which can be used to unit test private methods very easily. Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject is the fully qualified name. 
public class Maths
{
   private int CalculatePower(int Base, int Exponent)
   {
      int Product = 1;

      for (int i = 1; i <= Exponent; i++) 
      { 
         Product = Product * Base; 
      } 
      return Product; 
   } 


To unit test this method, We create an instance of the class and pass the created instance to the constructor of PrivateObject class. Then we use the instance of the PrivateObject class, to invoke the private method. The fully completed unit test is shown below.

[TestMethod()]
public void CalculatePowerTest()
{
   Maths mathsclassObject = new Maths();
   PrivateObject privateObject = new PrivateObject(mathsclassObject);
   object obj = privateObject.Invoke("CalculatePower", 2, 3);  

   Assert.AreEqual(8, (int)obj); 
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.