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.
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:
Notes:
- You must follow only this way to declare the parameter.
- Parameters are passes to class’s constructor to set in variables ad thus be available in test cases.
- The return type of parameter class is “List []”, data types to be used have been limited to String or primitive value



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
Posted by Fabio M. | 1 May, 2013, 1:04 pmHave you used Junit and dependencies version 4.11? As you see, i am using 4.11 here.
Posted by Lokesh Gupta | 1 May, 2013, 3:33 pm