Wednesday, 14 December 2011

Using a Test Matrix in NUnit


The conventional way of using NUnit is to write a separate method for each individual test of a method.

This can very quickly get unwieldy so I put together a simple example which creates and populates a test matrix of input parameters and expected results, which is then iterated through by one single [Test] method.

Firstly, we need a method to test, and this is it. As it is just for illustration I have kept it as simple as possible.

public class Methods
{
public int Add(int a, int b)
{
return a + b;
}
}


Then, within the unit tests project, we need a class with properties for the input parameters and expected result. It also has a property which is basically the other properties combined into a human-friendly string.

public class AddParameters
{
public int a { get; set; }
public int b { get; set; }
public int ExpectedResult { get; set; }

public string ParametersAsString
{
get
{
return "a: " + a.ToString() + ", b: " + b.ToString() + ", ExpectedResult: " + ExpectedResult.ToString();
}
}
}


The next step is to create a collection of AddParameters objects. This collection forms the test matrix itself. Giving the method the [SetUp] attribute forces NUnit to run it before running the tests.

List AddTestMatrix;

[SetUp]
public void CreateTestMatrix()
{
AddTestMatrix = new List();

AddTestMatrix.Add(new AddParameters { a = 1, b = 3, ExpectedResult = 4 });
AddTestMatrix.Add(new AddParameters { a = 3, b = 5, ExpectedResult = 8 });
AddTestMatrix.Add(new AddParameters { a = 9, b = -3, ExpectedResult = 6 });
AddTestMatrix.Add(new AddParameters { a = 22, b = 9, ExpectedResult = 31 });
AddTestMatrix.Add(new AddParameters { a = -77, b = 78, ExpectedResult = 1 });
}


Maintaining the matrix is as simple as editing this method.

The final step is to write a method to actually run the tests:

[Test]
public void TestAddUsingMatrix()
{
Methods methods = new Methods();

foreach (AddParameters ap in AddTestMatrix)
{
int Result = methods.Add(ap.a, ap.b);

Assert.That(Result, Is.EqualTo(ap.ExpectedResult), ap.ParametersAsString);
}
}

No comments:

Post a Comment