2009/10/28

The Data Generation Framework in MbUnit v3 (Part 1)

Gallio/MbUnit v3.1 has been released for a couple of weeks. But I just noticed that we did not speak too much about one of its nice additions: the Data Generation Framework. Jeff mentioned it in the release note, but I would like here to provide some more explanations.

The Data Generation Framework is a set of types present in the Gallio core component. The purpose is to ease the creation of predictable parameters for data driven tests. The feature can be used in MbUnit through a couple of new attributes. Today, we will have a look at [SequentialNumbers].

This attribute provides a column of sequential values. It must be applied against any parameter of a test method.
[TestFixture]
public class MyTestFixture
{
[Test]
public void MyTestMethod1([SequentialNumbers(Start = 0, End = 10, Count = 5)] decimal value)
{
// This test will run 5 times with the values 0, 2.5, 5, 7.5, and 10.
}

[Test]
public void MyTestMethod2([SequentialNumbers(Start = 1, Step = 1, Count = 4)] int value)
{
// This test will run 4 times with the values 1, 2, 3 and 4.
}

[Test]
public void MyTestMethod3([SequentialNumbers(Start = 0, End = 15, Step = 3)] double value)
{
// This test will run 6 times with the values 0, 3, 6, 9, 12, 15.
}
}
As you see, there are 3 possible way to configure the sequence, according the combination of properties you are going to initialized:
  • Start, Step, and Count.
  • Start, End, and Count.
  • Start, End, and Step

  • The attribute generates System.Decimal numbers, but you can use whatever primitive type with a lesser precision (double, int, byte, etc.)

    It is also possible to specify a hook method that is going to filter some specific numbers. The example below generates a sequence of numbers from 1 to 100, by excluding the values which are not divisible by 3 or by 10. The filter method should returns true to include the number in the sequence, or false to exclude it from the sequence.
    [TestFixture]
    public class MyTestFixture
    {
    [Test]
    public void Generate_filtered_sequence([SequentialNumbers(Start = 1, End = 100, Step = 1, Filter = "MyFilter")] int value)
    {
    // Code logic here...
    }

    public static bool MyFilter(int number)
    {
    return (n % 3 == 0) || (n % 10 == 0);
    }
    }

    No comments: