How to test Private methods using Visual Studio’s testing framework

 

I was recently asked how to test private methods in Visual Studio 2010 and 2012. Apparently, the supported approach has changed from previous versions.  Testing private methods can be done using the PrivateObject class. It’s pretty much like reflection, but it seemed simpler to me. See the example below. Class1 as a add method and addp (for private). The test method TstPrivateMethod tests addp.  

As a side note that using [assembly: InternalVisibleTo(“assembly”) allows a different assembly in this case UnitTestProject1 visibility to ClickOnceWithReadWrite internals.

Class1 the class to be tested

Class UnitTest1 the test class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("UnitTestProject1")]

namespace ClickOnceWithReadWrite

{

public class Class1

    {

public int add(int operand1, int operand2)

        {

return 0;

        }

private int addp(int operand1, int operand2)

        {

return 0;

        }

    }

}

using System;

using ClickOnceWithReadWrite;

using Microsoft.VisualStudio.TestTools.UnitTesting;  // Microsoft.VisualStudio.QualityTools.UnitTestFramework (in //Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll)

namespace UnitTestProject1

{

    [TestClass]

public class UnitTest1

    {

        [TestMethod]

public void TestMethod1()

        {

Class1 theTestClass = new Class1();

int theResult = theTestClass.add(5, 5);

Assert.AreEqual(theResult, 10);

        }

        [TestMethod]

public void TestPrivateMethod()

        {

PrivateObject pObj = new PrivateObject(new Class1());

Object[] arg = {5,5};

Object results = pObj.Invoke("addp",arg);

int intResult = (Int32)results;

Assert.AreEqual(intResult, 10);

        }

    }

}