Parameterized Unit Test with JUnit 4

Junit 4 has introduced a new feature Parameterized tests. These tests allow developer to run the same test many times using different values. To mark a test class as a parameterized test, you must first annotate it with @RunWith(Parameterized.class). The class must then provide at least three entities:

  • A static method that generates and returns test data (using @Parameters annotation),
  • A single constructor that stores the test data, and
  • A test method (using @Test annotation).

The method that generates test data must be annotated with @Parameters, and it must return a Collection of Arrays.

The JUnit parameterized test mechanism expects to instantiate the test class by calling a constructor that has the same number of arguments as there are elements in the current parameters array.

Following example shows how to use parameterized test.

package com.kruders.junit;

import static org.junit.Assert.*;

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 ParameterizedTest {
	private int number;
	private String expectedResult; 
	public ParameterizedTest(int number, String expectedResult) {
		this.number = number;
		this.expectedResult = expectedResult;
	}
	
	public String validateEven(int number) {
		if(number % 2 == 0)
			return "even";
		return "odd";
	}
	
	@Parameters
	public static Collection<Object[]> evenNumbers() {
		return Arrays.asList(new Object[][] { { 2 , "even" }, { 7 , "odd" }, { 12 , "even" }, { 16 , "even"} });
	}
	
	@Test
	public void testMethod() {
		System.out.println("Parameterized Number is : " + number);
	    assertEquals(expectedResult,validateEven(number));
	}
}


No comments yet.

Leave a Reply