Parameterized Unit Test

When you are writing unit tests, you want to test all the border cases. You can create a method for every border case, but sometimes this is a very repetitive job.

JUnit has a more pragmatic approach for these sorts of tests, called Parameterized tests. The idea is simple. You create your testcase with your test methods. You define a list of parameters that is given to the constructor and all the tests inside the testcase are executed for every parameter.

See this example. A simple class: Calculator

package be.styledideas.blog;

public class Calculator {
    public Long add(Long a, Long b){
        return a+b;
    }
}

I want to test this method with more than one parameter. I have created this parameterized unit test.

package be.styledideas.blog;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.ArrayList;
import java.util.Collection;

@RunWith(Parameterized.class)
public class CalculatorAddTestCase {
    private Long a;
    private Long b;
    private Long expected;

    public CalculatorAddTestCase(Long a, Long b, Long expected) {
        this.a = a;
        this.b = b;
        this.expected = expected;
    }

    @Test
    public void add() {
        Long actual = new Calculator().add(a, b);
        Assert.assertEquals(expected, actual);
    }

    @Parameterized.Parameters
    public static Collection<Object[]> getParameters(){
        Collection<Object[]> parameters = new ArrayList<Object[]>();
        parameters.add(new Object[]{1L, 2L, 3L});
        parameters.add(new Object[]{-1L, 2L, 1L});
        parameters.add(new Object[]{2L, 2L, 3L});
        parameters.add(new Object[]{4L, 0L, 4L});
        return parameters;
    }
}

The first thing that is different about this test is the @RunWith annotation at the top. Instead of the Junit4 runner, we use the Parameterized runner. This annotations looks for a static method that is annotated with the @Parameters annotation.
When we look closer at the getParameters method, we see that every item in the List maps to the constructor of the TestCase, so every item represents a running test. This concrete example results in equal to 4 unit tests.

Now you can be wondering what is the added value of this annotation over a list that you pass to your test. If you are just giving a test method a List with parameters, and one parameter creates a failure in your test, you will have to search for the test that is failing. When you execute it this way, any modern IDE will point which parameter is incorrect.

3 thoughts on “Parameterized Unit Test”

Leave a Reply

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

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=""> <s> <strike> <strong>