Translate

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.

[TestFixture(21)]
public class TestCaseFromAnotherClass
{
private int expectedValue;
public TestCaseFromAnotherClass(int x)
{
expectedValue=x;
}
[Test,TestCaseSource(typeof(Enumerator_GeneratesData), "GenerateData")]
public void TestCaseSourceTest(int arg1, int arg2)
{
Assert.That(arg1*arg2,Is.EqualTo(expectedValue));
}
}

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

[TestFixture(42)]
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: