Condividi tramite


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

        }

    }

}

Comments

  • Anonymous
    November 27, 2013
    Mine is telling me that "An object reference is required for the non-static field, method or property 'ClickOnceWithReadWrite.Class1.addp(int, int)' " (different names though)

  • Anonymous
    November 27, 2013
    Really useful blog post. thanks. Do you know how you would go about testing private static methods (i just made them non static, but thats not going to always work)

  • Anonymous
    December 17, 2013
    Thanks for the info. I suppose this'll have to do until VS regains 2010's ability to generate tests for non-public members. Why did that disappear? I've not seen one good explanation anywhere.

  • Anonymous
    May 25, 2015
    private object is running into System.MissingMethodException. Don't know how to deal with this. Private object is not able to locate the private function of class. Please help