Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 10 / Topic 7 of 12

Parameterized tests: one test body, many inputs

Four separate @Test methods that only differ in their numbers are four copies of the same bug waiting to happen when the formula changes. @ParameterizedTest runs one test body once per row of data.

@ParameterizedTest(name = "price {0}, {1}% off -> {2}")
@CsvSource({
        "1000.0,  0.0, 1180.0",
        "1000.0, 20.0,  944.0",
        "1000.0, 50.0,  590.0",
        "   0.0, 20.0,    0.0"
})
void finalPrice_variousDiscounts_matchExpected(double price, double percentOff, double expected) {
    assertEquals(expected, DiscountCalculator.finalPrice(price, percentOff), 0.001);
}

@CsvSource supplies one row per line, matched positionally to the method's parameters; name = "..." controls how each row is labelled in the report ({0}, {1}, {2} are the row's values, in order) — Section 12's tree shows all four rows as separate, individually pass/fail-able entries under one test method.

@ValueSource is simpler: one value per run, for a single parameter.

@ParameterizedTest(name = "percentOff {0} is out of range")
@ValueSource(doubles = {-1.0, 100.5, 250.0})
void finalPrice_percentOffOutOfRange_throwsForEveryValue(double percentOff) {
    assertThrows(IllegalArgumentException.class,
            () -> DiscountCalculator.finalPrice(1000.0, percentOff));
}

This one test body now proves the validation holds for three different bad inputs, each shown and judged separately in the report. (@MethodSource exists too, for data too irregular for one annotation line — point it at a static method that returns a stream/collection of arguments; not needed for anything in this lesson's examples, but worth knowing the name for when @CsvSource starts to feel cramped.)

Full program: examples/bank-and-discount/DiscountCalculatorTest.java.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide