Thursday, 2 July 2009

Generating test cases from an external class

The TestCaseSource attribute allows you to specify a method or a property, which could act as the source for your test cases. Simple and effective as TestCase attribute is TestCaseSource attribute is better.

A simpe rule that you must remember is that the class that contains a source method for the testCaseSource attribute must have a default constructor defined for it unlike the TestCase attribute.

// Class that uses another class' method as the source for its test method using the TestCaseSource attribute and taking the type and the name of the method as its arguments.

public class TestCaseFromAnotherClass
private int expectedValue;
public TestCaseFromAnotherClass(int x)
[Test,TestCaseSource(typeof(Enumerator_GeneratesData), "GenerateData")]
public void TestCaseSourceTest(int arg1, int arg2)

// Class that contains the source method for the TestCaseSource attribute and hence, must have a default constructor.

public class Enumerator_GeneratesData
private int expectedAnswer;

public Enumerator_GeneratesData() { expectedAnswer = 42; }
public Enumerator_GeneratesData(int val) { expectedAnswer = val; }
public IEnumerable GenerateData()
for (int i = 1; i <= expectedAnswer; i++)
if (expectedAnswer % i == 0)
yield return new int[] { i, expectedAnswer / i };

[Test, TestCaseSource("GenerateData")]
public void TestGeneratedData(int x1, int y1)
Assert.That(x1 * y1, Is.EqualTo(expectedAnswer));


No comments: