Wednesday, 31 March 2010

Testing Private Methods in .Net

Some developers seem to be against testing private methods, that if you need to test private methods there is a design issue. I don't think I agree in all cases and extracting some method logic into another method for further testing seems valid to me. Having to make that method public (against it's design) just for testing purposes doesn't sit right, so I test private methods using the PrivateObject class found in the Visual Studio TestTools library...

public void IsValidInput_NumberString_ReturnsTrue()
 // Arrange 
 var myClass = new MyClassWithPrivateMethod();
 var privateObject = new PrivateObject(myClass);

 // Act
 bool result = (bool)privateObject.Invoke("IsValidInput", new object[] { "123" });

 // Assert


  1. An alternative way is to make the method internal and make the test assembly a friend assembly in the AssemblyInfo.cs

  2. This is great unobtrusive way to test private methods. I don't believe that code should be structured for testing considerations.