Archive for February, 2015

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;

public class JunitTest

	private String code;
	private String description;

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

	 public static Collection getParameters() 
		 ArrayList<Object[]> paramList = new ArrayList<Object[]>();
		 return paramList;

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

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

	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.

Have a run with it!

Java, Software ,