Labels

Tuesday 18 December 2012

First step into Junit 4.10

Junit  is a very popular unit testing framework for Java applications which helps to build a fully automated unit tests.

The main objectives of any unit testing framework would be:
>> Each unit test should run independently of all other unit tests.
>> The framework should detect and report errors test by test.
>> It should be easy to define which unit tests will run.

Setting up Junit:
 Download the Junit JAR file from junit.org/downloads and add them into your projects compilation path.
If you are using windows shell, extract downloaded file into C:\ and run as below:



 If you are using any IDE's like Eclipse then right click on the project > Properties > Libraries > Add JARs





Lets create a java program for factorial:
Fact.java
public class Fact {

    public int factorial(int i){
        if (i < 1) throw new IllegalArgumentException();
        if (i ==1 ) return 1;
        return i*factorial(i-1);
       
    }
}

And its Junit cases which validates both positive and negative cases (given number less than 1).
FactTest.Java

import static org.junit.Assert.*;
import org.junit.Test;

public class FactTest {
    @Test
    public void testfactorial() {
        Fact f = new Fact();
        int res = f.factorial(2);
        assertEquals(2,res,0);
        int res1 = f.factorial(5);
        assertEquals(120,res1,0);
        //fail("Not yet implemented");
    }
    @Test
    public void testZero(){
        Fact f = new Fact();
    try{
        int res2=f.factorial(0);
    } catch (IllegalArgumentException e){
    }
    }
}

Right click the Junit test file and Run As 'Junit Test' and you will get the results as below:



Notes:
- In Junit 3.x version we needed to extends the TestCase class but it has been removed from Junit 4.
- It is good practice if the Junit class named as XXXTest and also its methods are named as testXxxx()
- Annotations are important for Junit tests and as soon as the program sees @Test, it will start executing the test.

Reference:
Junit pocket guide by Kent Beck