MbUnit TestSuite Attribute – Creating tests dynamically

I’ve been wanting to write about this for a while however haven’t really had the chance.  While prepping for a NxtGenUG session I came across the TestSuite attribute.  By using this, you can build up your tests to execute dynamically and provide the parameters when the tests are loaded into the runner and framework.  This allows for some great flexibility and extendibility, especially if you don’t know all of the possible test values at design-time and want values to be easily added (adding a row to the database, or dropping another file into a directory).

To take advantage of this, you need to use the TestSuiteFixtureAttribute at the top of your class.

public class TestSuiteTests

You can then create the test methods you want to be executed in order to test your system.  Two important points, they must take a parameter of type Object and return an Object – the rest is up to you. In the first test, I just write out the ToString value to the console,  in the second I check to see if the value is between 0 and 5.

public Object MethodUnderTest(object testData)
    Console.WriteLine(“MethodUnderTest Executed”);
    StringAssert.Contains(testData.ToString(), “Parameter”);
    return null;

public Object AnotherMethodUnderTest(object testData)
    string testDataString = testData.ToString();

    int testExecution = Convert.ToInt32(testDataString[testDataString.Length -1].ToString());
    Assert.Between(testExecution, 0, 5);

    return null;

The final stage is to create the method which will programmatically create all of your tests and test parameters.

The method below is marked with the TestSuiteAttribute so the framework knows this can create tests.  Inside the method, we create a new TestSuite object with a name to identify it, we can then add new items into the collection which are then returned to the framework and executed.  The parameters to add are:

  1. Name of test
  2. Method to call (the test itself) as a TestDelegate object
  3. Any parameters for the test

public ITestSuite Suite()
    TestSuite suite = new TestSuite(“NewSimpleSuite”);

    for (int i = 0; i < 10; i++)
        suite.Add(“MethodUnderTest” + i, new TestDelegate(this.MethodUnderTest), “Parameter” + i);
        suite.Add(“AnotherMethodUnderTest” + i, new TestDelegate(this.AnotherMethodUnderTest), “Parameter” + i);

    return suite;

The above code creates 20 tests, 10 for each test method. In the UI, the tests are all loaded correctly, as you can see each one is named correctly based on our code.


Very powerful attribute! But use the power wisely…

Download code sample here – http://blog.benhall.me.uk/Code/MbUnit/TestSuiteTests.cs.txt

Technorati Tags: ,,

Leave a Reply

Your email address will not be published. Required fields are marked *