Tuesday, September 3, 2013

JUnit Example by using Test runner


JUnit Example by using Test runner

Eclipse provides support for running test interactively in the Eclipse IDE. 

You can also run your JUnit tests outside Eclipse via standard Java code. The org.junit.runner.JUnitCore class provides the runClasses() method which allows you to run one or several tests classes. As a return parameter you receive an object of the type org.junit.runner.Result. This object can be used to retrieve information about the tests.

This will write potential failures to the console if any.

import java.util.ArrayList;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

/**
* @author sanjeeva
* assertEquals(String message, long expected, long actual)
* assertEquals(String message, Object expected, Object actual)
* Test runner is used for executing the test cases.
*/
public class ArrayListTest {

     private ArrayList<String> list; //Test fixtures

     //Initialize the test fixture before the Test method
     @Before
     public void init(){
          list = new ArrayList<String>();
          list.add("Sanjeeva"); //index[0]
          list.add("Pathirana"); //index[1]
     }

     // Test method to test the insert operation
     @Test
     public void insertTest() {
           // assertEquals(String message, long expected, long actual)
           Assert.assertEquals("wrong size", 2, list.size());
           list.add(2, "Chandima");
           Assert.assertEquals("wrong size", 3, list.size());
 
           // assertEquals(String message, Object expected, Object actual)
           Assert.assertEquals("wrong element", "Sanjeeva", list.get(0));
           Assert.assertEquals("wrong element", "Pathirana", list.get(1));
           Assert.assertEquals("wrong element", "Chandima", list.get(2));
     }

     // Test method to test the replace operation
     @Test
     public void replaceTest() {
           Assert.assertEquals("wrong size", 2, list.size());
           list.set(1, "Sandamali");
           Assert.assertEquals("wrong size", 2, list.size());
           Assert.assertEquals("wrong element", "Sanjeeva", list.get(0));
           Assert.assertEquals("wrong element", "Sandamali", list.get(1));
     }

     /**
     * @param args
     */
     public static void main(String[] args) {

          Result result = org.junit.runner.JUnitCore.runClasses(ArrayListTest.class);
          for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
     }

}