How to write parameterized testcases with junit 4

As a developer, we all have written Junit testcases at some stage of our career. They are like one strong pillar of your product development life cycle. We have also gone through best practices which are recommended depend on your needs.

Ads by Google

In this post, I will suggest you another way to test your code units. They are parameter based. They have been main feature in Junit 4. So, lets start by identifying junit 4 runtime dependencies.

Below are maven dependencies, you should add in your maven project before testing example code.

<!-- Junit -->
	  <dependency>
	    <groupid>junit</groupid>
	    <artifactid>junit</artifactid>
	    <version>4.11</version>
	    <scope>test</scope>
	</dependency>

	  <dependency>
	    <groupid>junit</groupid>
	    <artifactid>junit-dep</artifactid>
	    <version>4.11</version>
	    <scope>test</scope>
	</dependency>

Parameterized testcase make use of @RunWith and @Parameters annotations. Lets see how to use them.

Below is the test class, I will write test case for.

 

package corejava.test.junit;

public final class MathUtils {
	//Return square of a function
	public static int square(final int number) {
		return number * number;
	}
}

Lets write the testcases for above math utility class.


package corejava.test.junit;

import java.util.Arrays;

import org.junit.Assert;
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 JunitTestsWithParameters {

	// @Parameters annotation marks this method as parameters provider
	@Parameters(name = "Run #Square of : {0}^2={1}")
	public static Iterable<object []> data() {
		return Arrays.asList(new Object[][] { { 1, 1 }, { 2, 4 }, { 3, 19 },
				{ 4, 16 }, { 5, 25 } });
	}

	// Our two parameters
	private final int input;
	private final int resultExpected;

	// Constructor is initialized with one set of parameters everytime
	public JunitTestsWithParameters(final int input, final int result) {
		this.input = input;
		this.resultExpected = result;
	}

	@Test
	public void testUserMapping() {
		// You can use here assert also
		Assert.assertEquals(resultExpected, MathUtils.square(input));
	}
}

Result will look like this:

junit 4 test execution

Test execution result

Notes:

  1. You must follow only this way to declare the parameter.
  2. Parameters are passes to class’s constructor to set in variables ad thus be available in test cases.
  3. The return type of parameter class is “List []”, data types to be used have been limited to String or primitive value

 

 

 

Ads by Google

8 thoughts on “How to write parameterized testcases with junit 4”

  1. What about using JUnit Theory instead using Parameterized runner, @Parameters and @Parameter annotations ?

  2. Hi Lokesh, Thank you for your awesome tutorials!! I want to write Junit for my REST service. Could you please write an article on how to write unit test for REST services. Thanks in advance!!

  3. Hello

    I am facing three issues when parameterising my class
    Please help me !

    1.When parametrising my first test(first value) always fails and give the error–org.openqa.selenium.WebDriverException: unknown error: keys should be a string

    2.When accessing the excel sheet in some tests I am getting this error–java.lang.IllegalArgumentException: wrong number of arguments

    Any clue?

  4. Hi,

    Nice article !!

    I have problem with line 15 and the attribute name of the annotations Parameters.

    The compilator says : “The attribute Name is undefined for the annotation type Parameterized.Parameters”.

    Exists the attribute name in Parameters ?

    Ciao
    Fabio

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *


five − 3 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>