JUnit 4 Showcase – Parameterized Tests

A very interesting feature is the usage of parameterized tests to save us of the trouble of repetitive test code and automatically call test cases using predefined collection of test data.

Everything starts with the @RunWith(Parameterized.class) annotation that needs to be applied on the test class this time. A special public static method annotated as @Parameters signals the collection of test data. This set will be called by JUnit behind the scenes once per each data set calling the constructor for the creation of a new test class. The constructor should allocate this collection of test data into encapsulated members. These members would be used by the @Test annotated methods performing the test cases.

An example would look like this:

package com.dimitrisli.junitshowcase.parameterizedTest;

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

import junit.framework.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 ParameterizedTesting {

	@Parameters
	public static Collection<?> data(){
		return Arrays.asList(new Object[][]{
				{2,3,6},
				{3,4,12},
				{4,5,20},
				{5,6,30},
				{6,7,42}
		});
	}
	
	private int a;
	private int b;
	private int result;
	
	public ParameterizedTesting(int a, int b, int result){
		this.a = a;
		this.b = b;
		this.result = result;
	}
	
	@Test
	public void multiplicationCalculation(){
		int calcResult = a*b;
		System.out.println("a="+a+", b="+b+". Expected result= "+result+", and calculated result= "+calcResult);
		Assert.assertEquals(result, calcResult);
	}
	
}

that yields back the result:

a=2, b=3. Expected result= 6, and calculated result= 6
a=3, b=4. Expected result= 12, and calculated result= 12
a=4, b=5. Expected result= 20, and calculated result= 20
a=5, b=6. Expected result= 30, and calculated result= 30
a=6, b=7. Expected result= 42, and calculated result= 42

This code can be found in this Github repository.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s