How to Unit Test a Private Method with MSTest

Okay so I’m not going to get into the debate about whether or not private methods should be unit tested as that’s not the purpose of this post (for what it’s worth I think they shouldn’t be tested), but as MSTest provides functionality to test private methods it makes sense that I should know how to set a test up for the occasion where a client wants me to write unit tests for private methods.

How to do it

As per the title of this post and the content so far this assumes you’re using MSTest as your test environment.

First off, you need to create and make use of an instance of the PrivateObject class which is located within the Microsoft.VisualStudio.TestTools.UnitTesting namespace.

The PrivateObject class provides a mechanism for (as you might expect) testing methods which are not public. For more information on the PrivateObject class check out:

Code Example

private PrivateObject po;
public void InitializeTests()
   po = new PrivateObject(typeof(NameOfTheClassUnderTest);

public void CleanupTests()
   po = null;

public void MethodName_TestUndertaken_ExpectedResult()
   string expectedResult = "String1String2";
   // The object array matches the signature of the method
   //under test
   string actualResult = (string)po.Invoke("ConcatenateTwoStrings",      new object[] { "String1", "String2" });

   Assert.AreEqual(expectedResult, actualResult);

Leave a Reply

Your email address will not be published. Required fields are marked *