Monday, April 19, 2010

Unit test all enum values with NUnit

In an older post I demonstrated NUnit's built-in parameterized tests feature. This allows a developer to call a single method to run multiple tests.

Let's say I want to run the test for each value in an enumeration. Using the TestCase attribute, I can write the test like this:

  [TestCase(Powertools.Chainsaw)]
  [TestCase(Powertools.CircularSaw)]
  [TestCase(Powertools.PowerDrill)]
  public void PowerToolsTestExplicit(Powertools p)
  {
      // Do test
  }

Which is fine, but what if I add a new value to the enum? Instead of having to add another attribute to the test, it would be easier to loop over all enum values at runtime. With the TestCaseSource attribute I can do just that.

Within my unit test class I first create a method that returns an IEnumerable (in this case Array) containing the enum values:

  public Array GetPowerTools()
  {
      return Enum.GetValues(typeof(Powertools));
  }

Then I create my unit test and decorate it with the TestCaseSource attribute. The attribute constructor takes one parameter, sourceName, which is the name of the method to call:

  [TestCaseSource("GetPowerTools")]
  public void PowerToolsTestWithIEnumerable(Powertools p)
  {
      // Do test
  }

In either case, this expands my unit tests as expected. The second method is easier to maintain and less likely to allow untested code into the system.

1 comment:

  1. You can do the same using Theory attribute.

    [Theory]
    public void PowerToolsTestTheory(Powertools p)
    {
    // Do test
    }

    ReplyDelete

Note: Only a member of this blog may post a comment.