Monday 12 September 2016

Junit Parameterized Tests

Junit Testing framework allows us to use Parameters in out Test Class. To write Parameterized test case the Test Class should contain only one test case and we can provide multiple parameters for it as per given in our example below.

To notify that the particular class as parameterized test add annotation 
@RunWith(Parameterized.class) 

Such class need a static method with annotation @Parameters annotation. This method generates collection of arrays and each item in the collection is refereed as array. We can also use @Parameter annotation on public fields and inject test values in the test.

Let us see the following example to understand how to make use of Parameterized Junit Tests  -


import static org.junit.Assert.assertEquals;

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

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 ParameterizedTestUsingConstructor {

    private int num1;
    private int num2;

    public ParameterizedTestUsingConstructor(int p1, int p2) {
        num1 = p1;
        num2 = p2;
    }

    // creates the test data
    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] { { 1 , 2 }, { 5, 3 }, { 121, 4 } };
        return Arrays.asList(data);
    }


    @Test
    public void testMultiplyException() {
        MyClass tester = new MyClass();
        assertEquals("Result", num1 + num2, tester.add(num1, num2));
    }


    // class to be tested
    class MyClass {
        public int add(int i, int j) {
            return i + j;
        }
    }

}

The test case executes 3 times as per configured data set.



0 comments:

Post a Comment