Tuesday, September 3, 2013

JUnit – Exceptions Test


JUnit – Exceptions Test

JUnit provides a option of tracing the Exception handling of code. You can test the code whether code throws desired exception or not.

The expected parameter is used as follows @Test(expected) .
Below simple example explain how the @Test(expected) works in Junit.


import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class ExceptionTest {

      @Test(expected = ArithmeticException.class)
      public void divisionWithException() {
            int i = 1/0;
      }

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

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

JUnit – Time Test


JUnit – Time Test

If a test case takes more time than specified number of milliseconds then Junit will automatically terminated and mark it as failed.

The timeout parameter is used as follows @Test(timeout).

Below simple example explain how the @Test(timeout) works in Junit.


1. TestJUnitMessageUtil.java

public class TestJUnitMessageUtil {

       private String message;

       /**
       * Constructor
       * @param message
       */
       public TestJUnitMessageUtil(String message){
            this.message = message;
       }

       //Print the message
       public String printMessage(){
            return this.message;
       }

       //Print the modified message
       public String printModifiedMessage(){
           return "Hi " + this.message;
       }
}

2. TimeOutTest.java

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


public class TimeOutTest {

       TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

       @Test(timeout=1000)
       public void printMessage(){
             Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
       }

       @Test
       public void printModifiedMessage(){
            Assert.assertEquals("Hi Sanjeeva", messageUtil.printModifiedMessage());
       }

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

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

JUnit – Ignore Test


JUnit – Ignore Test

Sometimes our code is not ready, but test case written to test. Such a situation that method/code will fail if run. The @Ignore annotation helps in this regards.

JUnit engine will just bypass the method which annotate as ignore.

Below simple example explain how the @ignore works in Junit.


1. TestJUnitMessageUtil.java

public class TestJUnitMessageUtil {

     private String message;

     /**
     * Constructor
     * @param message
     */
     public TestJUnitMessageUtil(String message){
         this.message = message;
     }

     //Print the message
     public String printMessage(){    
          return this.message;
     }

     //Print the modified message
     public String printModifiedMessage(){
          return "Hi " + this.message;
     }
}

2. IgnoreTest.java

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;


public class IgnoreTest {

      TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

      @Ignore
      @Test
      public void printMessage(){
            Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
      }

     @Test
     public void printModifiedMessage(){
           Assert.assertEquals("Hi Sanjeeva", messageUtil.printModifiedMessage());
     }

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

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

}

JUnit - Test suite


JUnit - Test suit

Test suite : bundle a few unit test cases and run it together.

* In JUnit, both @RunWith and @SuiteClasses annotation are used to run the suite test.

Below simple example explain how the test suite works in Junit.


1. TestJUnitMessageUtil.java

public class TestJUnitMessageUtil {

        private String message;
        /**
        * Constructor
        * @param message
        */
 
       public TestJUnitMessageUtil(String message){
              this.message = message;
       }

      //Print the message
      public String printMessage(){
              return this.message;
      }

      //Print the modified message
      public String printModifiedMessage(){
              return "Hi " + this.message;
      }
}

2. TestJUnit01.java

import org.junit.Assert;
import org.junit.Test;

public class TestJUnit01 {

          TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");
 
          @Test
          public void testPrintMessage(){
                 Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
          }
}

3. TestJUnit02.java

import org.junit.Assert;
import org.junit.Test;

public class TestJUnit02 {

           TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

           @Test
           public void testPrintMessage(){
                 Assert.assertEquals("Hi Sanjeeva", messageUtil.printModifiedMessage());
           }
}

4. TestSuite.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({TestJUnit01.class,TestJUnit02.class})
public class TestSuite {

        public static void main(String[] args) {

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


JUnit Example - Parameterized Test


JUnit Example - Parameterized Test

Parameterized tests feature introduced in Junit 4.
Parameterized tests allow developer to run the same test over and over again using different values.

* This class can contain one test method and this method is executed with the different parameters provided.

There are five steps to create Parameterized tests. 

1. Annotate (mark) a test class as parameterized test with @RunWith annotation.
2. On that test class create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Each item in this collection / test data set is used as the parameters for the test method.
3. Create a constructor that store the values for each test.
The number of elements in each array provided by the method annotated with @Parameters must correspond to the number of parameters in the constructor of the class. The class is created for each parameter and the test values are passed via the constructor to the class.
4. Create an instance variable for each "column" of test data.
5. Create your tests case(s) using the instance variables as the source of the test data.


Example :
1. MultiplyClass.java

public class MultiplyClass {

       public int multiply(int x, int y){
               if(x > 999)
                      throw new IllegalArgumentException("x should be less than 1000.");
               return x*y;
       }
}

2. MultiplyParameterizedClassTest.java

import java.util.Arrays;
import java.util.Collection;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class MultiplyParameterizedClassTest {

       private int multiplier;

       public MultiplyParameterizedClassTest(int testParam){
             this.multiplier = testParam;
       }

//crate the test data
       @Parameters
       public static Collection<Object[]> collectionData(){

             Object[][] data = new Object[][]{{1},{2},{99},{185},{500},{799},{999},{1000}};
             return Arrays.asList(data);
       }

       @Test
       public void testMultiplication(){

               MultiplyClass multiplyClass = new MultiplyClass();
               Assert.assertEquals("Result", multiplier * multiplier, multiplyClass.multiply(multiplier, multiplier));
       }
}

JUnit Execution Procedure


JUnit Execution Procedure

Here is the execution procedure of methods in JUnit. Which means that which method is called first and which one after that.
1. @BeforeClass
2. @Before
3. @Test
4. @After
5. @AfterClass

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;


public class JunitExecutionProcedure {

    //Execute only once, in the starting
    @BeforeClass
    public static void beforeClass() {
         System.out.println("before class");
    }

    //Execute only once, in the end
    @AfterClass
    public static void afterClass() {
         System.out.println("after class");
    }

    //Execute for each test, before executing test
    @Before
   public void before() {
         System.out.println("before");
   }
 
    //Execute for each test, after executing test
    @After
    public void after() {
         System.out.println("after");
    }

    //Test case 1
   @Test
   public void testCase1() {
       System.out.println("test case 1");
   }

   //Test case 2
   @Test
   public void testCase2() {
        System.out.println("test case 2");
   }

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

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