Monday, August 15, 2011

Unit Testing in MVC

Unit testing is a tool which is for the ease of developers to test their progams. From its name it is clear to test the units (methods or actions) of program.

To create the unit test, user need to create a seprate project for it. For this they just need to right click on the desired method or action. In right click dropdown menu there will be an option to create the unit test. Users can also create the unit test for each method of class by right click on the class and then use the option of create unit test.

Unit test project class have an attribute TestClass in square bracess ([TestClass]), In case of N-Unit test this attribute replaced by [TestFixture]. The methods  of the unit test project have
attribute "[TestMethod"] and similarly N-unit have "[Test]" attribute for the N-Unit test class methods.

After creation of unit test project. Its time to write the logic for unit test methods. These unit test methods follow "AAA" rule. (Arrange, Act, Assertion)
i) Arrange
  Here we need to initialize the objects that we need to test or need to supply the required inputs.

ii) Act
   In act section action of created objects of part (i) will take an action. Action will be method call or a calculation.

iii) Assertion
 In assertion we need to compare the results created by step (ii) and expected results. If both are matched then test will be successfull.

To test these test methods. There is a tool in visual studio which is used to debug the unit test. To enable it go view tab and from toolbars select "Test Tools". If unit test method passes then status of debugger will be in green color with text "passed", In case of any failure it will in red color with text named as "failure" .