Wednesday 20 January 2010

Unit Testing with MbUnit


MbUnit is a better framework for Unit Testing and I really feel always very comfortable to use it. The new latest version comes up with really a cool user interface design name ‘Gallio. With the help of Gallio you can test your cases and also debug each case easily. I think I should stop boring you guys and let’s start on an example but first download the Gallio and Install it.

First we need to create some project to test so open a Visual Studio environment and create a new project of class library type and name it as Calculator:

Now rename the Class1 to Calculation and a method for addition which is Add:

public class Calculation

{

///

/// To add two numbers

///

///

///

/// decimal

public static decimal Add(decimal a, decimal b)

{

return (a + b);

}

}


Now this method doesn’t do anything special it just add two numbers and we are going to test it with our Unit Test. I know this is not a great example but this is the simplest one.

Now add a project type of MbUnit V3 Test Project and name it as Calculator.Test:



After adding this project just add a normal C# class to this Test project and name it as UnitTest1 and add the following namespaces on top first:

using MbUnit.Framework;


After adding this namespace copy and paste the following code:

public UnitTest1()

{

}

[Test]

[Row(5.0,6.0,11.0)]

public static void TestAdditionPassed(decimal a, decimal b, decimal expected)

{

decimal sum = a + b;

Assert.AreEqual(sum,expected);

}

[Test]

[Row(5.0, 6.0, 14.0)]

public static void TestAdditionFailed(decimal a, decimal b, decimal expected)

{

decimal sum = a + b;

Assert.AreNotEqual(sum, expected);

}


Now here what we did so far added two test method one is for pass and one to fail and with Row attribute we define the row to test which get the value from row for example in first method the row is:

[Row(5.0,6.0,11.0)]


Here 5.0 is the first parameter of the method ‘TestAdditionPassed’ which is ‘a’, 6.0 is ‘b’ and 11.0 is parameter ‘expected’. Now after adding a and b we used Assert.AreEqual which checks two values and return bool if both are equal otherwise return false if both are not equal opposite to this we have another method which we used in second method ‘TestAdditionFailed’ which is Assert.AreNotEqual so if bots values are different it returns ‘true’ otherwise ‘false’.

Now build the project and open the Icarus GUI Test Runner from Programs:


Click on Add files and add the .dll file of your project from Calculator\bin\Debug:


Now click on start and you will see the following window:

Now the green tick shows here that all tests are passed.

Will come back soon with more details on Unit Testing. Thanks to all.