Test Driven Development

Test Driven Development

The first obvious question is, why it is called test driven development. Normally, we code  first and then we write test cases for it using white box or black box testing techniques. So, in normal course of action, development drives testing. But, in test driven development, the test cases are written first before writing the code.

Why Test cases are written before coding?

In normal development, we may forget to write test cases after writing code. Some time, we may be lazy to write test cases and some time we may run short of time. But in test driven development, when we write the test case first, we may never forget to write the code. As the compiler will keep on giving out error unless we write the code for which the test had already been written. There are unit testing frameworks for almost all the high level languages. Let’s see an example of Java.

Test Driven Development in Java using JUnit.

Java has many unit testing frameworks. The detail can be found at the following link.
https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#Java
JUnit is the most famous. Let’s use JUnit as an example. Suppose we are planning to write a class name MyCalc which would perform basic mathematical operation of addition, subtraction etc. But before writing that class, we would write the test class for it.

Line 1: The testing in which this class is residing
Line2 & 3: The imports required for testing
Line 6: @Test is annotation. Annotations in java have very special role. When we add annotation to a method, it changes the role of that method. In this example, the annotation, makes the method as test method. It means, the method will execute only in testing perspective. This method will never execute in normal execution of the application. It will only be executed when we would run the application in testing mode.
Line 7: The TestAdd is a test method for actual method Add().
Line 8: We created the object of the class under testing
Line 9: We call the method Add() by passing two arguments
Line 10: It is a method which is used to compare the actual results with expected results. AssertEqual compared two values. These values may be number, strings, floats or even arrays.There are also static asserting methods like assertTrue() assertFalse which can be used to compare the expected boolean values and actual outputs.
Line 14-20: Another testing method for actual method sub().

So, we have successfully written a test class for some assumed actual class. The compiler would be given errors at lines 8,10, 16 and 18. To fix these errors, let’s write the actual code.

Java – JUnit example in Eclipse with screen shots

 

 

Java – JUnit example in NetBeans with screen shots