Why do it in the hard way : A guide to JUnit Parameterized Tests

If you have a set of parameters that your method should be tested, here is an easy way. For an example, let’s take that you have a method to find a number is even or not. You want to test that for some random set of given numbers, whether the method works fine.

The method in Java to find even numbers looks like this:

public class EvenNumberChecker {
public boolean checkForEvenNumber(int number){
boolean isEven=false;
System.out.println("Number "+number+" is Even");
System.out.println("Number "+number+" is Odd");
return isEven;

Then here is where the magic comes in. You have to create a JUnit test case and annotate it with @RunWith(Parameterized.class). Then you have to create the constructor using the parameters to be tested as an arguments. Then annotate a method with @Parameterized.Parameters and add the parameters to be tested through this method. You have to be careful that this method should return an iterable list. Here is what the whole test case looks like.

public class TestEvenNumberChecker {
private EvenNumberChecker evenNumberChecker;
private Integer inputNumber;
private boolean isEven;

public void initialize() {
evenNumberChecker = new EvenNumberChecker();

// Parameter to be tested should be an argument here.
// In this case we have two parameters, that is the input number and the boolean value of indicating whether the number is even.
public TestEvenNumberChecker(Integer inputNumber,boolean isEven) {
this.inputNumber = inputNumber;

// We have to add the parameters to be tested through this method
public static Collection Numbers() {
return Arrays.asList(new Object[][]{{2314,true},{456834,true},{678423,false},{4632489,false}});

public void testPrimeNumberChecker() {
System.out.println(“Checking Number : “+inputNumber);
assertEquals(isEven, evenNumberChecker.checkForEvenNumber(inputNumber));

You can download the full implementation at https://github.com/sandarumk/ParameterizedTestTutorial


One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s