Show List

JUnit parameterized tests

JUnit parameterized tests allow developers to run the same test case multiple times with different sets of inputs. This is useful when a test case needs to be run with multiple sets of data to verify that the code works correctly for all input scenarios.

To write a parameterized test in JUnit, you need to create a test class that extends org.junit.runners.Parameterized and annotate it with @RunWith(Parameterized.class). You also need to define a public static Collection<Object[]> data() method that returns a collection of arrays of objects, where each array represents a set of inputs for the test case.

Here is an example of a parameterized JUnit test:

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

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class ExampleParameterizedTest {
    private int input;
    private int expectedResult;

    public ExampleParameterizedTest(int input, int expectedResult) {
        this.input = input;
        this.expectedResult = expectedResult;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                { 0, 0 },
                { 1, 1 },
                { 2, 4 },
                { 3, 9 },
                { 4, 16 }
        });
    }

    @Test
    public void testSquare() {
        int result = input * input;
        assertEquals(expectedResult, result);
    }
}

In this example, the test case is a method named testSquare that tests the square of a number. The input and expected result for each test case are defined in the data method, which returns a collection of arrays of objects. When the test is executed, JUnit will run the testSquare method once for each array in the collection, using the values from the array as the inputs for the test.

This way, the same test case can be run with different sets of inputs, making it easier to verify that the code works correctly for all scenarios.


    Leave a Comment


  • captcha text