junit

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

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button