HI WELCOME TO SIRIS

Unit Testing a private static method in C# .NET

Leave a Comment


In the previous article we have seen how to unit test private instance methods. In this article we will see unit testing static private methods

In general, to unit test a static public method, we invoke the respective method using the
class name in our test method. We then simply check for the expected and actual output. However, when it comes to unit testing a static private method, we cannot do the same, as the private members are not available outside the class. To make the process of unit testing static private members easier, microsoft unit testing framework has provided PrivateType class.


In the example below, CalculatePower() is a private static method. The purpose of this method is to calculate the value, when a given number is raised to a certain power. For example 2 to the power of 3 should return 8 and 3 to the power of 2 sholuld return 9. So to unit test this method we create the instance of PrivateType class. To the constructor of the PrivateType class we pass the type of the class that contains the private static method that we want to unit test. We do this by using the typeof keyword. The PrivateType instance can then be used to invoke the private static method that is contained with in the Maths class. The Maths class that contains the static private CalculatePower() method and the unit test are shown below.

public class Maths
{
   private static int CalculatePower(int Base, int Exponent)
   {
      int Product = 1;


      for (int i = 1; i <= Exponent; i++)
      { 

         Product = Product * Base; 
      } 
      return Product; 
   } 


[TestMethod()]
public void CalculatePowerTest()
{
   PrivateType privateTypeObject = new PrivateType(typeof(Maths));
   object obj = privateTypeObject.InvokeStatic("CalculatePower", 2, 3);

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

0 comments:

Post a Comment

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