Wednesday, August 15, 2007

Test driven development in dot net using NUnit - part1

hi,
I am back with another post today.
we will be discussing about Test Driven Development (TDD).

well the first question is What is TDD?
TDD is the process of developing a software so that the unit testing of the code can be done using some tools (like NUnit or JUnit).

so if use TDD do we have to test in the whole software delivered to the customer ?
YES, we will have to test the whole component after the software is developed.This test will be done to assure that the software is working as per expectations.
but what we must understand is that a software is as good as its individual components.If one of the components of a software is not working fine,then the whole system fails.
a set of classes constitute a component. class will have a set of functions. so we write classes and functions and then we use TDD to test these functions. This assures us that the minute parts of the system are working fine.

but we will have to follow some Object Oriented guidelines for using TDD:

1) we should eliminate the duplication of code. i mean to say that a function should not be repeated elsewhere in the particular component. This assures us of optimal reuse.So we should make sure that classes do not have common methods.

2) if an operation is being performed in several different places, then it is better to create a function for this operation and call that function.
Reason : let us consider a scenario where we are doing a string comparison in several different places.example
str.ToUpper()==str2.ToUpper().
now at a later point of time i realize that i have to change this, then i will have to make the changes at several different places where i am doing this operation.

3) Every operation or action being performed should be broken down in to a single individual function so that it will be easy to test that particular functionality.
example :
factorial of 5 = 5*4*3*2*1 = 120
we do code for this as

public int factorial(int num)
{
int result =1;
while (num>1)
{
result = result * num;
num= num-1;
}
return result;
}

but now if the factorial function for 5 returns 60 instead of 120,what may be the reason?
we will have to debug and find out.
if there any other way?can we just see the test results and ascertain where it fails?
can we make this more testable?
yes, we can create two new functions -for multiply and then subtract.

public int factorial(int num)
{
int result =1;
while (num>1)
{
result = multiply(result,num);
num= subtract(num,1);
}
}
public int Multiply(int num1,int num2)
{
return num1* num2;
}

public int Subtract(int num1,int num2)
{
return num1-num2;
}


so now it becomes easy for us to test the factorial functionality. the advantage being if the factorial function is not giving the expected results, then we can find out where it fails by the tests for multiply and subtract functions.

in my next post, we can discuss how to use NUnit for testing.

No comments: