Unit Testing a Private Method

With Visual Studio keep changing the way you create unit tests I thought I’d document down how to test a private method the easy way.

Here is a simple HomeController and we want to test that the GetPageSize method return 20 in a unit test.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var pageSize = GetPageSize();
        return View(pageSize);
    }

    private int GetPageSize()
    {
        return 20;
    }
}

As GetPageSize is a private method we’ll need to use the PrivateObject class to return the methods result, this is quite easy, from the Unit Test project make sure you have a reference to your MVC project and then reference the HomeController and invoke the method you need the result back from:

[TestMethod]
public void CheckPageSizeIs20()
{
    PrivateObject privateObject = new PrivateObject(typeof(HomeController));
    int pageSize;
    pageSize = (int)privateObject.Invoke("GetPageSize");

    Assert.AreEqual(20, pageSize);
}

If you need to pass in parameters to the private method then you can pass in an anonymous type

var actual = (IEnumerable<ActivityData>)privateObject.Invoke("GetAllUnassignedJobs", new object[] { filterData, uniqueJobs });

Reference: How to test a class member that is not public

Thanks to Karthik for googleing the answer