Test Driven Development in .Net

As part of software development life cycle developers have to create unit test to test their code before QA start testing the software. TDD (Test driven development) is one of the core practice for XP (extreme programming) Software methodology.

TDD is widely adopted by java community but very less in .net programmers. But day by day .net community is also growing and for .net developers also have different tools for TDD.

So what is Unit Test?

According to Ron Jeffries, Unit Tests are “programs written to run in batches and test classes. Each typically sends a class a fixed message and verifies it returns the predicted answer.

in practical term developer has to write a piece of code the test the result of each public interface of the class to test the behaviour and the match with expected result.

so, let’s say class employee have method called insert(…) ,update(..), delete(..), GetAll(..).

Each method should have respective test method. To Test insert(..) method, we call the insert(..) method and to verify the result check get the total number of employees which should be increased by one.

In .net there are many unit testing framework out there but i will use NUnit Framework for this post.

In NUnit, we have [TestFixure] attribute to declare any call as test class and [Test] attribute for to declare method as test method.

for employee test class sample c# code look like this.


import Nunit.Framework;
[testfixture]
public class testemployee
{
[test]
public void Insert()
{
Employee emp = new Employee{FirstName=”Peter”, LastName=”White”};
_db.Employee.Insert(emp);
// assume there are 9 employee in database
Assert.Equal(10,_db.Employee.GetAll());
}
[test]
public void Update()
{
Employee emp = _db.Employee.GetById(10);
emp.FirstName = “David”;
_db.Employee.Save(emp);
emp = _db.GetById(10);
Assert.Equal(“David”,emp.FirstName);
}
[test]
public void Delete()
{
Employee emp = _db.Employee.GetById(5);
_db.Employee.delete(emp);
// assume there are 10 employee in database
Assert.Equal(9,_db.Employee.GetAll());
}
}

Note that the testemployee class should be public as well as  test method.
Sometimes we also need to setup few variables and classes to instantiate object. Let’s say to get employees count from database we need to pass db connection string. NUnit have [Setup] and [TearDown] attribute to handle before and after configurations.

[Setup]
public void initDB()
{
_db = new DatabaseContext(dbconnectionstring);
}
[Setup]
public void initCounter()
{
}
[TearDown]
public void resetCounter()
{
}

How to start TDD ?
TDD is not follow the converntional method of development where developer writes an application and then it get tested. In TDD the the whole cycle is follow the reverse path. Developers have to write a code for unit testing first and then implement the actual functionality.

for instance we want to create class called employee which do the CRUD operation. the employee class contains Inser, Update, Delete, GetByID and GetAll method. Before we create actual class create a test class called testemployee. you can give name what ever suits you. And create test method testInsert, testUpdate, testDelete, testGetbyId, testGetAll. And now run the test and let it fail. Because it wouldn’t find the class called employee. Now create a class called employee and create dummy methods. When you run the test it will run successfully. But we haven’t implement the functionality yet. Now implement the class method and run the test it should get successful. If any of the test failed then fix the method and re run. In short to follow TDD you have to follow steps like:

1. write a test
2. run test and let it fail.
3. write test class and method without any implementation so the test class can compile.
4. run the test and let it fail again because it don’t have real implementation of methods.
5. implement methods so it can pass the test.
6. run the test and it should passed. it test fails then fix the method.
7. follow the step from 1 to 6 for new class.

Write Test for user Interface:

Testing data and business layer of application would  be most convenient task for developers because you have predefine classes and methods with arguments and return value. But most donutting task in web development is test the user interface or in short website. But thanks to the community members, WatiN(pronounce Waat-in) is one of the best web application testing framework I have found.

you can either use NUnit for Test and WatiN for UI test or just for UI test you can also just use WatiN.

with NUnit the test method will look like:


[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();

Assert.IsTrue(browser.ContainsText(“WatiN”));
}
}

(** source from http://watin.sourceforge.net)

without NUnit the test class look like:

using System;
using WatiN.Core;
namespace WatiNGettingStarted
{
class WatiNConsoleExample
{
[STAThread]
static void Main(string[] args)
{
// Open a new Internet Explorer window and
// goto the google website.
IE ie = new IE("http://www.google.com");
// Find the search text field and type Watin in it.
ie.TextField(Find.ByName("q")).TypeText("WatiN");
// Click the Google search button.
ie.Button(Find.ByValue("Google Search")).Click();
// Internet Explorer and the console window immediately.
ie.Close();
}
}
}

(** source from http://watin.sourceforge.net)

In summary, as a developer think how you can make your code more maintainable and testable. TDD is one the technique you can follow to improve the quality of your code.

Leave your comments if you find the post is helpful.

References:

NUnit : Unit Testing framework in .net

Watin: UI test framework in .net