Books MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Support Us

Unit Test private method in C# .NET


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. Click here, to read an articel on, unit testing a private static method with an example.

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);
}

No comments:

Post a Comment

If you are aware of any other C# questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us