Friday, October 1, 2010

Howto create unit test for privat, internal, and friend methods

Problem: You have a class with a private method that you wish to test.
public class ClassUnderTest
{
  private int DoSomePrivateStuff()
  {
     // Something is happening here
  }
} 
Since the method is private you can not access the it from the outside of the object.

How I solved this earlier was to make a testable class that inherited from the class I wanted to test.
public class TestableClassUnderTest : ClassUnderTest
{
  public int DoSomePrivateStuff()
  {
     base.DoSomePrivateStuff();
  }
} 

I now could do the following.
[TestClass]
public class ClassUnderTestTests
{
  [TestMethod]
  public void DoSomePrivateStuff_WhenCalled_ReturnsZero()
  {
     //Arrange
     var testClass = new TestableClassUnderTest();
     //Act
     var actual = testClass.DoSomePrivateStuff();
     //Assert
     Assert.AreEqual(0, actual);
  }
}

This is the classic Extract and Override pattern and there is nothing wrong with it.
But as a colleague showed me today, there is another way when you are using Visual Studio.
  1. Goto the ClassUnderTest in visual studio and right click. Select "Create Private Accessor" and select the test project you want this accessor in.
  2. Go to the test project you choose in step 1. You will now have a project folder called "Test References" with one file ending with ".accessor".
And that's it. VS have now created a class for you with the name "_accessor" that you can use in your tests. My example from above can now be rewritten to the following:
[TestClass]
public class ClassUnderTestTests
{
  [TestMethod]
  public void DoSomePrivateStuff_WhenCalled_ReturnsZero()
  {
     //Arrange
     var testClass = new ClassUnderTest_accessor();
     //Act
     var actual = testClass.DoSomePrivateStuff();
     //Assert
     Assert.AreEqual(0, actual);
  }
}
What's nice about this is that you don't need to create a bunch of testable classes. They are automagically created with reflection for you. Now you got more time to do fun stuff.... :-)

You can read more about this here: http://msdn.microsoft.com/en-us/library/bb385974.aspx

Share:

0 kommentarer:

Post a Comment