Parameterized tests

suggest change

Parameterized tests execute a single test method multiple times across different sets of input parameters and expected outcomes. Instead of copying and pasting assertions or wrapping tests in clumsy loops, modern Java testing frameworks—most notably JUnit 5 (Jupiter)—provide first-class annotations for data-driven testing.


1. Setting Up JUnit 5 Parameterized Tests

To enable parameterized testing in Maven or Gradle, include junit-jupiter-params:

<!-- In pom.xml -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.14.4</version>
    <scope>test</scope>
</dependency>

2. Basic Parameterized Test with @ValueSource

@ValueSource is the simplest source provider, feeding an array of literal primitive or string values one by one:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class StringUtilsTest {

    public static boolean isPalindrome(String input) {
        if (input == null) return false;
        String clean = input.replaceAll("\\s+", "").toLowerCase();
        return clean.equals(new StringBuilder(clean).reverse().toString());
    }

    @ParameterizedTest
    @ValueSource(strings = { "racecar", "radar", "level", "kayak", "rotator" })
    void shouldRecognizeValidPalindromes(String candidate) {
        assertTrue(StringUtilsTest.isPalindrome(candidate));
    }

    @ParameterizedTest
    @ValueSource(ints = { 2, 4, 6, 8, 10, 42 })
    void shouldRecognizeEvenNumbers(int number) {
        assertTrue(number % 2 == 0);
    }
}

Testing Null, Empty, and Blank Inputs

JUnit 5 provides dedicated annotations to test edge cases:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class BlankStringTest {

    @ParameterizedTest
    @NullAndEmptySource // Supplies null and "" (empty string)
    @ValueSource(strings = { "   ", "\t", "\n" }) // Also supplies blank whitespace strings
    void shouldReturnTrueForBlankStrings(String input) {
        assertTrue(input == null || input.isBlank());
    }
}

3. Tabular Inputs with @CsvSource

When each test iteration requires multiple parameters (e.g., input values paired with an expected result), use @CsvSource:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @ParameterizedTest(name = "[{index}] {0} + {1} = {2}")
    @CsvSource({
        "1,   1,   2",
        "5,   3,   8",
        "-10, 25,  15",
        "0,   0,   0"
    })
    void shouldAddNumbersCorrectly(int a, int b, int expected) {
        assertEquals(expected, a + b);
    }
}

Loading External Test Data with @CsvFileSource

For large test suites, test cases can be separated from code into a .csv file in your classpath resources (e.g., src/test/resources/data.csv):

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

class ShippingRateTest {

    @ParameterizedTest
    @CsvFileSource(resources = "/shipping_rates.csv", numLinesToSkip = 1)
    void shouldCalculateShippingFee(String countryCode, double weightKg, double expectedRate) {
        // ...
    }
}

4. Complex Data Structures with @MethodSource

When test arguments cannot be expressed as simple literals (e.g., complex domain objects, streams, or collections), @MethodSource references a static factory method returning a Stream<Arguments>:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.List;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;

class OrderDiscountTest {

    record Customer(String tier, int ordersCount) {}

    // Factory method providing argument tuples
    static Stream<Arguments> provideCustomersAndDiscounts() {
        return Stream.of(
            Arguments.of(new Customer("STANDARD", 1), 0.00),
            Arguments.of(new Customer("SILVER", 5),   0.05),
            Arguments.of(new Customer("GOLD", 15),    0.15),
            Arguments.of(new Customer("PLATINUM", 50), 0.25)
        );
    }

    @ParameterizedTest(name = "Customer tier {0} should receive {1} discount")
    @MethodSource("provideCustomersAndDiscounts")
    void shouldCalculateExpectedDiscount(Customer customer, double expectedDiscount) {
        double discount = calculateDiscount(customer);
        assertEquals(expectedDiscount, discount, 0.001);
    }

    private double calculateDiscount(Customer c) {
        return switch (c.tier()) {
            case "SILVER" -> 0.05;
            case "GOLD" -> 0.15;
            case "PLATINUM" -> 0.25;
            default -> 0.00;
        };
    }
}

5. Enum Arguments with @EnumSource

To run tests across all values of an enum:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

enum UserRole { GUEST, USER, ADMIN, SUPERADMIN }

class AuthorizationTest {

    @ParameterizedTest
    @EnumSource(value = UserRole.class, names = { "ADMIN", "SUPERADMIN" })
    void shouldAllowAccessForPrivilegedRoles(UserRole role) {
        assertTrue(role == UserRole.ADMIN || role == UserRole.SUPERADMIN);
    }
}

6. Summary and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents