Tuesday, June 23, 2009

My Unit Testing Naming Conventions

There is plenty of information on unit testing and unit test patterns, and I am by no means an expert.  But as I've started doing more tests, I've started using some naming conventions I find useful.  Here's how my unit tests generally look:

[TestFixture]
public class NnnTests
{
    [Test]
    public void Should_Do_XYZ_If_ABC()
    {
        var target = new SomethingBeingTested();
        var actual = target.DoSomething();
        Assert.AreEqual(expected, actual);
    }
}

 

This illustrates a few conventions:

  • Name the test fixture SomethingTests, where Something is the main target class being tested.
  • Name each method in plain English with underscores, adding qualifiers if needed.  This is to avoid ambiguity if a word is legitimately camel-cased. For example in SomeMethodShouldReturnExpectedValue, it's not immediately clear that the method's name is "SomeMethod".  In SomeMethod_Should_Return_Expected_Value, this is not an issue.
  • Setup the test by setting a local variable named 'target'.
  • Get a result by calling a method on the target and setting a local variable named actual.
  • Assert one thing about the result.  This doesn't necessarily mean only one call to Assert.  Just that you look at the value of one narrowly scoped test.

I find that by following these, it keeps tests focused on a single test case and helps make them very readable.

No comments: