JUnit parameterized test

The parameterized test is a new feature introduced in JUnit 4. It provides the facility to execute the same test case again and again with different values.

Steps to create a parameterized test:

1. Test class have to be annotated with @RunWith(Parameterized.class) annotation.

2. Create a public static method with @Parameters annotation which returns a collection of objects as test data set.

3. Create data members for each column of test data set.

4. Create a public constructor which takes one object of test data set.

5. Create test case using test data set.

Example:

DivisionTestCase.java

import java.util.Arrays;
import java.util.Collection;
import com.w3schools.business.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.Parameterized;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
 
/**
 * This is test case class for parameterised test case.
 * @author w3schools
 */
@RunWith(Parameterized.class)
public class DivisionTestCase {
	 private int num1;
	 private int num2;
	 private int expectedResult;
	 private DivisionTest divisionTest;
 
	 //Constructor that takes test data.
	 public DivisionTestCase(int num1, int num2, 
			 int expectedResult){
		 this.num1 = num1;
		 this.num2 = num2;
		 this.expectedResult = expectedResult;
	 }
 
	 //called before every test case.
	 @Before
	 public void initializeDivisionTest() {
		 divisionTest = new DivisionTest();
	 }
 
	 //It will initialise parameters every 
	 //time trigger executes.
	 @Parameterized.Parameters
     public static Collection primeNumbers() {
        return Arrays.asList(new Object[][] {
           { 10, 2, 5 },
           { 20, 5, 4 },
           { 20, 10, 2 },
           { 40, 10, 20 }
        });
     }
 
	//Test case for division
	@Test
	public void test() {
		System.out.println("Parameterized Numbers: num1 = "
	           + num1 + ", num2 = " + num2);
		assertEquals(expectedResult, divisionTest
				.division(num1, num2));
	}
}

DivisionTest.java

/**
 * This is simple java class containing division method.
 * @author w3schools
 */
public class DivisionTest {	
	//division method
	public int division(int num1, int num2) 
			throws ArithmeticException{
		return num1/num2;
	}
}

Output:

Parameterized Numbers: num1 = 10, num2 = 2
Parameterized Numbers: num1 = 20, num2 = 5
Parameterized Numbers: num1 = 20, num2 = 10
Parameterized Numbers: num1 = 40, num2 = 10

junit7

 

Download this example.
 
Next Topic: Junit test runner.
Previous Topic: JUnit suite test.