JUnit Parameterized alternative

Oct 03, 2017

Parameterized tests in JUnit require adding @RunWith(Parameterized.class) and one or more @Parameters annotations, along with a method that returns the data, as described in the official JUnit parameterized tests documentation.

An alternative way is having the data inside the test method where it's within view. It keeps the code shorter due to less boilerplate, and makes it easy to locate and modify values. If more than one method needs to access the test data, it can be extracted into a static readonly field.

import org.junit.Test;

import java.util.ArrayList;

import static org.junit.Assert.assertEquals;

public class ParameterizedTestExample {

    public static void exampleTest() {

        // Data

        // 1: some integer, 2: some double, 3: some string, 4: expected value
        ArrayList testValues = new ArrayList() {{
            add(new Object[]{1, 0.2937, "foo", true});
            add(new Object[]{2, 0.8543, "bar", false});
            add(new Object[]{4, 0.9437, "baz", true});

        // Loop through data

        for (Object[] valueSet : testValues) {
            // Retrieve and cast data

            int someInt = (int) valueSet[0];
            double someDouble = (double) valueSet[1];
            String someString = (String) valueSet[2];
            boolean expected = (boolean) valueSet[3];

            // Execute within loop

            boolean actual = methodUnderTest(someInt, someDouble, someString);

            // Assert within loop

            assertEquals(expected, actual);
comments powered by Disqus