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
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;
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.
public void CalculatePowerTest()
Maths mathsclassObject = new Maths();
PrivateObject privateObject = new PrivateObject(mathsclassObject);
object obj = privateObject.Invoke("CalculatePower", 2, 3);