Saturday, May 7, 2005

Unit Testing Void Methods

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/unit_testing_void_methods.htm]

I was recently asked the good question "Should you create tests for void methods?". My answer: It depends. Let's look at the following example:

public class Foo1
{
    public Foo1()
    {
        _intCounter = 0;
    }

    private int _intCounter;
    public int Counter
    {
        get
        {
            return _intCounter;
        }
    }

    public void Increment()
    {
        _intCounter++;
    }

}

In this case, the void method Increment() changes the state of the Foo1 object, which can be measured by the Counter property. So, the following would be a decent test:

[Test] public void TestVoidMethod()
{
    Foo1 f = new Foo1();
    Assert.AreEqual(0,f.Counter);
    f.Increment();
    Assert.AreEqual(1,f.Counter);
}

The intent is that we want to always test deterministic logic, such as code that contains conditions, loops, or operators. While this is straight-forward with static functions (plug in x, get y), it can still apply to void methods. The difference is that a void method may be updating another property of an instantiated object instead of a return value.

However note that void methods may lack any logic to test. For example, the method below simply wraps some architecture block that writes out files. There's no logic here to test.

public void WriteFile(string strContent)
{
    ArchitectureBlock.WriteToFile(strContent);
}

No comments:

Post a Comment