Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

JUnit Parameterized Test Example

In this example we are going to see how to create a parameterized test in JUnit testing framework.

1. Create the java class to be tested

Create a folder named JUnitParameterized. This is the folder where your classes will be located. Using a text editor, create a Java class named Addition.java. To make sure your file name is Addition.java, (not Addition.java.txt), first choose “Save as -> Save as type -> All files”, then type in the file name Addition.java.
 
 
Addition.java

public class Addition {
    public int addNumbers(int a, int b){
        int sum = a + b;
        return sum; 
    }
}

2. Create JUnit test case

In the same directory (JUnitParameterized), use a text editor and create a java class named JunitAdditionTest.java with the following code.

JunitAdditionTest.java

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 JunitAdditionTest {

	private int expected;
	private int first;
	private int second;

	public JunitAdditionTest(int expectedResult, int firstNumber,
			int secondNumber) {
		this.expected = expectedResult;
		this.first = firstNumber;
		this.second = secondNumber;
	}

	@Parameters
	public static Collection<Integer[]> addedNumbers() {
		return Arrays.asList(new Integer[][] { { 3, 1, 2 }, { 5, 2, 3 },
				{ 7, 3, 4 }, { 9, 4, 5 }, });
	}

	@Test
	public void sum() {
		Addition add = new Addition();
		System.out.println("Addition with parameters : " + first + " and "
				+ second);
		assertEquals(expected, add.AddNumbers(first, second));
	}
}

A test class can be considered as parameterized test if the following requirements are fulfilled:

  • The class is annotated with @RunWith(Parameterized.class)

When a class is annotated with @RunWith, JUnit will invoke the class in which is annotated to run the tests, instead of using the runner built into JUnit.
Parameterized is a runner inside JUnit that will run the same test case with different set of inputs.

  • The class has a single constructor that stores the test data.
  • The class has a static method that generates and returns test data.

The method that generates test data (in our case this method is addedNumbers()) must be annotated with @Parameters, and it must return a Collection of Arrays. Each array represents the data to be used in each test execution. The number of elements in each array must be the same with the number of parameters in constructor.

  • The class has a test.

The test method is the method annotated with @Test annotation.

For further details regarding the @Test annotation, the assertEquals assertion (which are also mentioned in our code) and other JUnit Assertions and Annotations, you can have a look at JUnit using Assertions and Annotations Example.

3. Run your test case from the command line

You can run your JUnit test outside Eclipse, by using the org.junit.runner.JUnitCore class. This class provides the runClasses() method which allows you to execute one or several test classes. The return type of runClasses() method is an object of the type org.junit.runner.Result. This object can be used to collect information about the tests. Also, in case there is a failed test, you can use the object org.junit.runner.notification.Failure which holds description of the failed tests.

The procedure below shows how to run your test outside Eclipse.

In the directory JUnitParameterized, use a text editor and create a new Java class named JunitAdditionTestRunner.java with the following code.

JunitAdditionTestRunner.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class JunitAdditionTestRunner {

	public static void main(String[] args) {

		Result result = JUnitCore.runClasses(JunitAdditionTest.class);
		for (Failure fail : result.getFailures()) {
			System.out.println(fail.toString());
		}
		if (result.wasSuccessful()) {
			System.out.println("All tests finished successfully...");
		}
	}
}
  • Open command prompt and move down directories so as to find the directory where your java classes are located:
C:\Users\konstantina>cd JUnitParameterized

Attention: If your classes are located inside a package, for example package com.javacodegeeks.core.junit, you can have a look at JUnit Ignore Test Example, where we describe exactly what you should do in that case.

  • When JUnitParameterized is your current directory, compile all the classes in the directory

Attention: To run your JUnit tests outside Eclipse properly you need to add the needed JUnit library jars to the classpath of your program. You can find those library jars here.

C:\Users\konstantina\JUnitParameterized>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; Addition.java JunitAdditionTest.java JunitAdditionTestRunner.java
  • Now run the JunitAdditionTestRunner
C:\Users\konstantina\JUnitParameterized>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitAdditionTestRunner

  • Output:
Addition with parameters : 1 and 2
Addition with parameters : 2 and 3
Addition with parameters : 3 and 4
Addition with parameters : 4 and 5
All tests finished successfully...

As we see in the output, the test case is executed four times, which is the provided number of inputs in the method annotated with @Parameters annotation.

Download the source code

This was an example of parameterized test in JUnit testing framework.
Download the source code of this example : JUnitParameterized.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close