Thursday, June 12, 2008

MbUnit 2.4 - Avoiding Crappy Data Resulted From The Test

One of the nice features in MBUnit 2.4, is the ability to rollback the crappy data in the database resulted from running subsequent test methods. This is really interesting because this crappy data can become a nightmare during the application development or even after the deployment. You will spend pretty much time exploring your data to filter the dirty ones which can lead sometimes to some mistakes.

MbUnit give you the ability to rollback any changes made in the database during the test. Using MbUnit 2.4, this can be done by referring MBUnit.Framework.2.0 in the project references and using RollBack2 attribute for each test method.

public void InsertNewProductTest()
      Product product = Product.CreateNew('Nokia 800', 2300, true);

      Assert.AreEqual('Nokia 800', product.Name);
      Assert.AreEqual(2300, product.Price);
      Assert.AreEqual(true, product.InStock)


In the later example, any changes made in the database by persisting the Product object will be rolled back after the test execution. This will keep your tables clean containing only your application live data.

MBUnit uses TransactionScope in System.Transactions to provide the rollback functionality. However, you will need to set some security configurations for the DTC settings in order to make the TransactionScope properly work. To set these settings, open the Component Services in the Administrative tools. Then, show the properties of your computer and select MSDTC tab. Open the Security configurations and setup the needed settings for the remote and local authorization of the transactions on your machine.

As a side note, you are able to track the operating transactions by putting some break points inside your test method. Then, in the Component Services under the Transaction list you will find your active transactions listed there. More so you can check the Transaction Statistics to track the committed and aborted transactions of your test operations.


Anonymous said...

Dear Mohamed,
While this is great for small volumes of insertion, It gave us a problem when we were running simultaneous unit tests against a SQL Server database. I believe the error we got was "transport level error" and there was no solution to the problem at the time.

Mohammed Nour said...

I am not sure. But I believe this can be occurred esp. if there is a heavy load on the network or the db you make the transaction to.

Ricardo Fiel said...

Hi! I was a fan of the RollBack2 attribute until I started testing DBs with several millions of records. Then it was timeout nightmare.

But for small things, rocks!