Home > Java, Software > Quick Guide to JUnit multiple parameter tests with Parameterized annotation

Quick Guide to JUnit multiple parameter tests with Parameterized annotation

February 15th, 2015


It is extremely easy to create JUnit test classes to run and test your application or Java code.
JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.
All it needs is to include the JUnit library and use the @Test annotation for the method you need to run as test.
However, sometimes we need the convenience of the same test method to run with different parameters.
Following is an example how it can be done easily with some changes to a single test method by adding @RunWith(Parameterized.class) before the class name and then initialize a collection of parameters with @Parameters.
You can also read the parameters from a data provider once using a initializing method with @BeforeClass.

package net.marvinlee.test;
 
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Assert;
import org.junit.BeforeClass;
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 JunitTest
{

	private String code;
	private String description;
	

	public JunitTest(String code, String description)
	{
		super();
		this.code = code;
		this.description = description;
	}

	 @Parameters
	 public static Collection getParameters() 
	 { 
		 ArrayList<Object[]> paramList = new ArrayList<Object[]>();
		 addTestcases(paramList);
		 return paramList;
	 }

	protected static void addTestcases(ArrayList<Object[]> paramList)
	{
		for(int i=1;i<=10;i++)
		{
			paramList.add(new Object[]{"Code" + i, "Description " + i});
		}
	}

	@BeforeClass
	public static void init() 
	{ 
		System.out.println("Current dir:" +  JunitTest.class.getClassLoader().getResource("").getPath()); 
	}
	 

	@Test
	public void validateCases() 
	{
		boolean matched = ((code.equals("Code5") && description.equals("Description 5"))
			|| (code.equals("Code6") && description.equals("Description 6")));
		Assert.assertTrue("Failed test=" + code, matched);
		 
	}
	 
}

JUnit test classes can be run with Eclipse IDE and the above test class will show run results similar to the following screenshot.
Only the 4th and 5th testcases that match with the hardcoded values will pass while we get remaining 8 failures.
junit

Have a run with it!

 Follow me on twitter.





Java, Software

,

You might like the following posts too :

  • » Redis in Action by Josiah L. Carlson
  • » Redis Cookbook by Tiago Macedo, Fred Oliveira
  • » Continuous Enterprise Development in Java by Andrew Lee Rubinger, Aslak Knutsen
  • » Developer Programs
  • » Running JUnit tests in Maven with Surefire Plugin and skipTests in default packaging
    1. No comments yet.
    1. No trackbacks yet.