Tuesday, September 3, 2013

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));
       }
}