Parameterized JUnit Tests

Useful when multiple tests have the same structure, but have different inputs and produce different results. Here’s the skeleton:

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 SumTests
{
	@Parameters(name="{index}: {0}+{1}={2}") // name is optional, {index} will be used by default; arguments used here must be declared in constructor
	public static Collection<Object[]> data() 
	{
		return Arrays.asList(
			new Object[][] 
			{ 
				{1, 1, 2},
				{3, 5, 2}, // fails
				{-1, 1, 0}
			}
		);
	}

	public SumTests(int a, int b, int sum)
	{
		this.a = a;
		this.b = b;
		this.sum = sum;
	}

	@Test
	public void sum()
	{
		assertEquals("Sum is not correct", sum, a + b);
	}
	
	private int a, b, sum;
}
Advertisements
Parameterized JUnit Tests

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