JUnit Parameterized Tests

Su Suriya Ravichandran Updated 18 Nov 2026
16 min read ·Lesson 253 of 306

JUnit parameterized tests run the same test method many times with different input values. Instead of copying a test five times to check five inputs, you write it once with @ParameterizedTest and supply the inputs from a source such as @ValueSource or @CsvSource.

This lesson covers every common argument source in JUnit 6: @ValueSource, @NullSource and @EmptySource, @EnumSource, @CsvSource, @CsvFileSource and @MethodSource. It also shows custom display names, automatic argument conversion, ArgumentsAccessor and @ParameterizedClass, and ends with a fully parameterized test for a shipping cost calculator. The checks inside each test use JUnit Assertions.


Why Use JUnit Parameterized Tests

Here is a test for a simple even-number check, written without parameters:

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

import org.junit.jupiter.api.Test;

class EvenNumberTest {

    boolean isEven(int number) {
        return number % 2 == 0;
    }

    @Test
    void twoIsEven() { assertTrue(isEven(2)); }

    @Test
    void fourIsEven() { assertTrue(isEven(4)); }

    @Test
    void zeroIsEven() { assertTrue(isEven(0)); }

    @Test
    void minusSixIsEven() { assertTrue(isEven(-6)); }
}

Output (mvn test, shortened):

[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • The four tests are identical except for one number.
  • Adding a fifth case means copying a whole method again.
  • A parameterized test replaces all four with one method and a list of values, while still reporting each value as a separate test.

Your First @ParameterizedTest

A parameterized test uses @ParameterizedTest instead of @Test, plus at least one source annotation that supplies the arguments. The method declares a parameter to receive each value.

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

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

class EvenNumberParameterizedTest {

    boolean isEven(int number) {
        return number % 2 == 0;
    }

    @ParameterizedTest
    @ValueSource(ints = {2, 4, 0, -6})
    void numbersAreEven(int number) {
        assertTrue(isEven(number), number + " should be even");
    }
}

Output in the Console Launcher:

└─ numbersAreEven(int) ✔
   ├─ [1] 2 ✔
   ├─ [2] 4 ✔
   ├─ [3] 0 ✔
   └─ [4] -6 ✔

How it works:

  • JUnit calls numbersAreEven four times, passing 2, 4, 0 and -6 in turn.
  • Each call is reported as its own test with an index, so a failure tells you exactly which value broke.
  • The annotations live in the org.junit.jupiter.params package. The junit-jupiter dependency from Java JUnit Basics already includes it.

Note: If your build compiles with the -parameters flag, the default display name also includes the parameter name, for example [1] number=2.


Supply Simple Values With @ValueSource

@ValueSource provides a single argument per invocation from an array of literals. It supports these types:

AttributeType
ints, longs, shorts, bytesInteger types
doubles, floatsFloating-point types
chars, booleanschar, boolean
stringsString
classesClass<?>
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

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

class EmailValidatorTest {

    boolean isValidEmail(String email) {
        return email != null && email.matches("^[\\w.+-]+@[\\w-]+(\\.[\\w-]+)+$");
    }

    @ParameterizedTest(name = "{0} is valid")
    @ValueSource(strings = {"asha@example.com", "ravi.k+java@gocourse.in", "meena_2026@mail.co.uk"})
    void acceptsValidEmails(String email) {
        assertTrue(isValidEmail(email));
    }

    @ParameterizedTest(name = "{0} is rejected")
    @ValueSource(strings = {"asha", "asha@", "@example.com", "asha@@example.com", "asha@example"})
    void rejectsInvalidEmails(String email) {
        assertFalse(isValidEmail(email));
    }
}

Output in the Console Launcher (shortened):

├─ acceptsValidEmails(String) ✔
│  ├─ "asha@example.com" is valid ✔
│  ├─ "ravi.k+java@gocourse.in" is valid ✔
│  └─ "meena_2026@mail.co.uk" is valid ✔
└─ rejectsInvalidEmails(String) ✔
   ├─ "asha" is rejected ✔
   ├─ "asha@" is rejected ✔
   ...

How it works:

  • The name attribute sets a custom display name. {0} is replaced by the first argument.
  • JUnit 6 wraps text arguments in double quotes in display names, which makes empty strings and spaces visible.
  • Splitting valid and invalid inputs into two tests keeps each assertion simple.

Test null and Empty Values With @NullSource and @EmptySource

@ValueSource cannot supply null, because annotation values cannot be null. Use these sources instead, often combined with @ValueSource:

SourceSupplies
@NullSourceA single null
@EmptySourceAn empty value: "", empty list, set, map or array
@NullAndEmptySourceBoth of the above
import static org.junit.jupiter.api.Assertions.assertTrue;

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

class BlankNameTest {

    boolean isBlankName(String name) {
        return name == null || name.isBlank();
    }

    @ParameterizedTest(name = "[{index}] {0}")
    @NullAndEmptySource
    @ValueSource(strings = {" ", "   ", "\t", "\n"})
    void blankNamesAreDetected(String name) {
        assertTrue(isBlankName(name));
    }
}

Output in the Console Launcher:

└─ blankNamesAreDetected(String) ✔
   ├─ [1] null ✔
   ├─ [2] "" ✔
   ├─ [3] " " ✔
   ├─ [4] "   " ✔
   ├─ [5] "\t" ✔
   └─ [6] "\n" ✔

How it works:

  • @NullAndEmptySource adds null and "" before the four @ValueSource values, giving six invocations.
  • Escape sequences such as \t and \n are shown escaped in display names, so invisible characters are easy to spot in reports.
  • Without the name == null check, the null case would fail with a NullPointerException, which is exactly the kind of bug this source finds.

Test Every Enum Constant With @EnumSource

@EnumSource passes enum constants to the test. By default it passes all of them; names and mode let you choose a subset.

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

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

class OrderStatusTest {

    enum OrderStatus { CREATED, PAID, SHIPPED, DELIVERED, CANCELLED, REFUNDED }

    boolean canCancel(OrderStatus status) {
        return status == OrderStatus.CREATED || status == OrderStatus.PAID;
    }

    @ParameterizedTest
    @EnumSource(value = OrderStatus.class, names = {"CREATED", "PAID"})
    void earlyOrdersCanBeCancelled(OrderStatus status) {
        assertTrue(canCancel(status));
    }

    @ParameterizedTest
    @EnumSource(value = OrderStatus.class, names = {"CREATED", "PAID"}, mode = Mode.EXCLUDE)
    void laterOrdersCannotBeCancelled(OrderStatus status) {
        assertFalse(canCancel(status));
    }
}

Output in the Console Launcher:

├─ earlyOrdersCanBeCancelled(OrderStatus) ✔
│  ├─ [1] CREATED ✔
│  └─ [2] PAID ✔
└─ laterOrdersCannotBeCancelled(OrderStatus) ✔
   ├─ [1] SHIPPED ✔
   ├─ [2] DELIVERED ✔
   ├─ [3] CANCELLED ✔
   └─ [4] REFUNDED ✔

How it works:

  • The first test receives only the two named constants.
  • Mode.EXCLUDE gives every constant except the named ones. If someone adds a new status such as RETURNED, it is tested automatically.
  • Other modes include MATCH_ALL and MATCH_ANY, which select constants by regular expression.

Pass Several Arguments With @CsvSource

Most tests need more than one value: an input and an expected result. @CsvSource supplies rows of comma-separated values, one row per invocation.

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

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

class GradeTest {

    String gradeFor(int marks) {
        if (marks >= 90) return "A";
        if (marks >= 75) return "B";
        if (marks >= 60) return "C";
        if (marks >= 40) return "D";
        return "F";
    }

    @ParameterizedTest(name = "{0} marks -> grade {1}")
    @CsvSource({
        "100, A",
        "90,  A",
        "89,  B",
        "75,  B",
        "60,  C",
        "40,  D",
        "39,  F",
        "0,   F"
    })
    void gradeBoundaries(int marks, String expectedGrade) {
        assertEquals(expectedGrade, gradeFor(marks));
    }
}

Output in the Console Launcher (shortened):

└─ gradeBoundaries(int, String) ✔
   ├─ "100" marks -> grade "A" ✔
   ├─ "90" marks -> grade "A" ✔
   ├─ "89" marks -> grade "B" ✔
   ...
   └─ "0" marks -> grade "F" ✔

How it works:

  • Each string is one row. JUnit splits it at commas and trims spaces, so extra spaces for alignment are fine.
  • The text "90" is converted to int automatically because the parameter is an int. Display names show the original CSV text, so numbers appear in quotes too.
  • Grade boundaries are classic places for off-by-one bugs, and this table checks both sides of each one in a single readable block.

Quoting, Empty Values and Text Blocks

@CsvSource has a few rules for special values:

RowArguments received
"apple, banana""apple", "banana"
"'Chennai, TN', 600001""Chennai, TN", "600001" (single quotes protect the comma)
"Asha, ''""Asha", "" (empty quotes give an empty string)
"Asha, ""Asha", null (a missing value gives null)

For larger tables, use a Java text block with a header row:

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

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

class FullNameTest {

    String fullName(String first, String last) {
        return last == null ? first : first + " " + last;
    }

    @ParameterizedTest
    @CsvSource(useHeadersInDisplayName = true, textBlock = """
        FIRST,  LAST,     EXPECTED
        Asha,   Kumar,    Asha Kumar
        Ravi,   ,         Ravi
        Meena,  'S. Rao', Meena S. Rao
        """)
    void joinsNames(String first, String last, String expected) {
        assertEquals(expected, fullName(first, last));
    }
}

Output in the Console Launcher:

└─ joinsNames(String, String, String) ✔
   ├─ [1] FIRST = "Asha", LAST = "Kumar", EXPECTED = "Asha Kumar" ✔
   ├─ [2] FIRST = "Ravi", LAST = null, EXPECTED = "Ravi" ✔
   └─ [3] FIRST = "Meena", LAST = "S. Rao", EXPECTED = "Meena S. Rao" ✔

How it works:

  • useHeadersInDisplayName = true treats the first row as column names and shows them in the report.
  • The empty LAST value in the second row becomes null, which tests the last == null branch.
  • Text blocks make the table easy to read and edit, like a small spreadsheet inside the test.

Load Test Data From a File With @CsvFileSource

When the table grows to dozens of rows, move it into a CSV file under src/test/resources.

src/test/resources/pin-codes.csv:

pin,city
600001,Chennai
560001,Bengaluru
110001,New Delhi
400001,Mumbai
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Map;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

class PinCodeTest {

    private static final Map<String, String> CITY_BY_PIN = Map.of(
            "600001", "Chennai", "560001", "Bengaluru",
            "110001", "New Delhi", "400001", "Mumbai");

    @ParameterizedTest(name = "PIN {0} -> {1}")
    @CsvFileSource(resources = "/pin-codes.csv", numLinesToSkip = 1)
    void findsCityForPin(String pin, String expectedCity) {
        assertEquals(expectedCity, CITY_BY_PIN.get(pin));
    }
}

Output in the Console Launcher:

└─ findsCityForPin(String, String) ✔
   ├─ PIN "600001" -> "Chennai" ✔
   ├─ PIN "560001" -> "Bengaluru" ✔
   ├─ PIN "110001" -> "New Delhi" ✔
   └─ PIN "400001" -> "Mumbai" ✔

How it works:

  • resources = "/pin-codes.csv" loads the file from the test classpath, which Maven and Gradle build from src/test/resources.
  • numLinesToSkip = 1 skips the header row.
  • Non-developers, such as a QA team, can add rows to the CSV without touching Java code.

Build Complex Arguments With @MethodSource

Annotations can only hold constants. When arguments are objects, lists, or values calculated in code, use @MethodSource. It points to a static method that returns a stream of arguments.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.argumentSet;
import static org.junit.jupiter.params.provider.Arguments.arguments;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CartTotalTest {

    long total(List<Long> pricesInPaise) {
        return pricesInPaise.stream().mapToLong(Long::longValue).sum();
    }

    static Stream<Arguments> carts() {
        return Stream.of(
                arguments(List.of(), 0L),
                arguments(List.of(49_900L), 49_900L),
                arguments(List.of(49_900L, 129_900L, 9_900L), 189_700L));
    }

    @ParameterizedTest
    @MethodSource("carts")
    void addsAllPrices(List<Long> prices, long expectedTotal) {
        assertEquals(expectedTotal, total(prices));
    }

    static Stream<Arguments> namedCarts() {
        return Stream.of(
                argumentSet("empty cart", List.of(), 0L),
                argumentSet("one book", List.of(49_900L), 49_900L),
                argumentSet("book, keyboard and pen", List.of(49_900L, 129_900L, 9_900L), 189_700L));
    }

    @ParameterizedTest
    @MethodSource("namedCarts")
    void addsAllPricesWithNames(List<Long> prices, long expectedTotal) {
        assertEquals(expectedTotal, total(prices));
    }
}

Output in the Console Launcher:

├─ addsAllPrices(List, long) ✔
│  ├─ [1] [], 0 ✔
│  ├─ [2] [49900], 49900 ✔
│  └─ [3] [49900, 129900, 9900], 189700 ✔
└─ addsAllPricesWithNames(List, long) ✔
   ├─ [1] empty cart ✔
   ├─ [2] one book ✔
   └─ [3] book, keyboard and pen ✔

How it works:

  • carts() returns a Stream<Arguments>. Each arguments(...) call creates one invocation with its values in parameter order.
  • argumentSet("name", ...) attaches a readable name to a set of arguments. The default display name uses it instead of printing the raw values.
  • If you omit the method name, as in @MethodSource, JUnit looks for a factory method with the same name as the test.
  • A method in another class is referenced as "com.gocourse.TestData#carts".

Note: For a single parameter, the factory method can return a plain Stream<String>, List<Integer> or array instead of Stream<Arguments>.


Automatic Argument Conversion

JUnit converts the text values from @ValueSource, @CsvSource and @CsvFileSource to the parameter's type automatically.

Parameter typeExample source text
int, long, double, boolean"42", "3.14", "true"
Any enum"PAID"
java.time.LocalDate, LocalTime, Duration"2026-11-17", "09:30", "PT15M"
java.math.BigDecimal"499.00"
Any class with a String constructor or static valueOf(String)Depends on the class
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.DayOfWeek;
import java.time.LocalDate;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class DueDateTest {

    LocalDate dueDate(LocalDate issued, int days) {
        return issued.plusDays(days);
    }

    @ParameterizedTest(name = "{0} + {1} days = {2} ({3})")
    @CsvSource({
        "2026-11-17, 14, 2026-12-01, TUESDAY",
        "2026-12-25, 10, 2027-01-04, MONDAY",
        "2028-02-20, 10, 2028-03-01, WEDNESDAY"
    })
    void calculatesDueDate(LocalDate issued, int days, LocalDate expected, DayOfWeek expectedDay) {
        LocalDate due = dueDate(issued, days);
        assertEquals(expected, due);
        assertEquals(expectedDay, due.getDayOfWeek());
    }
}

Output in the Console Launcher:

└─ calculatesDueDate(LocalDate, int, LocalDate, DayOfWeek) ✔
   ├─ "2026-11-17" + "14" days = "2026-12-01" ("TUESDAY") ✔
   ├─ "2026-12-25" + "10" days = "2027-01-04" ("MONDAY") ✔
   └─ "2028-02-20" + "10" days = "2028-03-01" ("WEDNESDAY") ✔

How it works:

  • JUnit parses "2026-11-17" into a LocalDate and "TUESDAY" into a DayOfWeek without any extra code.
  • The last row crosses February in the leap year 2028, which has 29 days, so the due date is 1 March.
  • Display names show the original source text in quotes, which is why the numbers and dates appear quoted here.

Read Arguments With ArgumentsAccessor

When a row has many columns, listing every one as a parameter becomes long. An ArgumentsAccessor parameter receives the whole row, and you read values by index and type.

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

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

class InvoiceLineTest {

    record InvoiceLine(String product, int quantity, long unitPriceInPaise, int gstPercent) {
        long totalInPaise() {
            long net = quantity * unitPriceInPaise;
            return net + net * gstPercent / 100;
        }
    }

    @ParameterizedTest(name = "{0}")
    @CsvSource({
        "Java Book, 2, 50000, 5,  105000",
        "Keyboard,  1, 120000, 18, 141600",
        "Course,    3, 100000, 18, 354000"
    })
    void calculatesLineTotal(ArgumentsAccessor row) {
        InvoiceLine line = new InvoiceLine(
                row.getString(0),
                row.getInteger(1),
                row.getLong(2),
                row.getInteger(3));

        assertEquals(row.getLong(4), line.totalInPaise());
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • row.getInteger(1) reads column 1 and converts it, using the same rules as automatic conversion.
  • The test builds a domain object from the row, then checks its calculated total. For example, 2 × 500.00 + 5 % GST = 1,050.00, which is 105000 paise.
  • For reuse across tests, an ArgumentsAggregator with @AggregateWith can turn a row into an object automatically.

Run a Whole Class With Different Inputs Using @ParameterizedClass

@ParameterizedClass parameterizes an entire test class. Every @Test method in the class runs once for each set of arguments. This is useful when several tests share the same input.

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedClass;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedClass
@ValueSource(strings = {"racecar", "madam", "level"})
class PalindromeWordTest {

    private final String word;

    PalindromeWordTest(String word) {
        this.word = word;
    }

    @Test
    void readsTheSameBackwards() {
        assertEquals(word, new StringBuilder(word).reverse().toString());
    }

    @Test
    void hasOddLength() {
        assertTrue(word.length() % 2 == 1);
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • JUnit creates the class three times, passing each word to the constructor.
  • Both test methods run for each word, so 3 words × 2 tests = 6 tests.
  • Without @ParameterizedClass, you would need a @ParameterizedTest with the same source on every method.

Real-World Example: JUnit Parameterized Tests for a Shipping Calculator

An online store charges shipping by zone and weight, with free shipping above an order value. The rules have many combinations, which makes them a natural fit for parameterized tests.

package com.gocourse.shipping;

public class ShippingCalculator {

    public enum Zone { LOCAL, REGIONAL, NATIONAL }

    public static final long FREE_SHIPPING_ABOVE_PAISE = 99_900;

    public long shippingInPaise(Zone zone, int weightInGrams, long orderValueInPaise) {
        if (weightInGrams <= 0) {
            throw new IllegalArgumentException("Weight must be positive: " + weightInGrams);
        }
        if (orderValueInPaise > FREE_SHIPPING_ABOVE_PAISE) {
            return 0;
        }
        long base = switch (zone) {
            case LOCAL -> 4_000;
            case REGIONAL -> 6_000;
            case NATIONAL -> 9_000;
        };
        int extraHalfKilos = (weightInGrams - 1) / 500;   // first 500 g included
        return base + extraHalfKilos * 2_000L;
    }
}
package com.gocourse.shipping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.params.provider.Arguments.argumentSet;

import com.gocourse.shipping.ShippingCalculator.Zone;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

@DisplayName("ShippingCalculator")
class ShippingCalculatorTest {

    private final ShippingCalculator calculator = new ShippingCalculator();

    @ParameterizedTest(name = "{0}, {1} g -> ₹{3} paise")
    @CsvSource(textBlock = """
        # zone,     grams, orderValue, expectedPaise
        LOCAL,      500,   20000,      4000
        LOCAL,      501,   20000,      6000
        REGIONAL,   1000,  50000,      8000
        REGIONAL,   1001,  50000,      10000
        NATIONAL,   250,   99900,      9000
        NATIONAL,   2500,  10000,      17000
        """)
    @DisplayName("charges base rate plus 20.00 per extra 500 g")
    void chargesByZoneAndWeight(Zone zone, int grams, long orderValue, long expectedPaise) {
        assertEquals(expectedPaise, calculator.shippingInPaise(zone, grams, orderValue));
    }

    @ParameterizedTest
    @EnumSource(Zone.class)
    @DisplayName("ships free in every zone above 999.00")
    void freeShippingInEveryZone(Zone zone) {
        assertEquals(0, calculator.shippingInPaise(zone, 3_000, 100_000));
    }

    @ParameterizedTest(name = "{0} g is rejected")
    @ValueSource(ints = {0, -1, -500})
    @DisplayName("rejects zero and negative weights")
    void rejectsInvalidWeight(int grams) {
        IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
                () -> calculator.shippingInPaise(Zone.LOCAL, grams, 10_000));
        assertEquals("Weight must be positive: " + grams, error.getMessage());
    }

    static Stream<Arguments> freeShippingBoundary() {
        long limit = ShippingCalculator.FREE_SHIPPING_ABOVE_PAISE;
        return Stream.of(
                argumentSet("one paisa below the limit", limit - 1, 9_000L),
                argumentSet("exactly the limit", limit, 9_000L),
                argumentSet("one paisa above the limit", limit + 1, 0L));
    }

    @ParameterizedTest
    @MethodSource("freeShippingBoundary")
    @DisplayName("free shipping starts just above 999.00")
    void freeShippingBoundary(long orderValue, long expectedPaise) {
        assertEquals(expectedPaise, calculator.shippingInPaise(Zone.NATIONAL, 400, orderValue));
    }
}

Output in the Console Launcher:

└─ ShippingCalculator ✔
   ├─ charges base rate plus 20.00 per extra 500 g ✔
   │  ├─ "LOCAL", "500" g -> ₹"4000" paise ✔
   │  ├─ "LOCAL", "501" g -> ₹"6000" paise ✔
   │  ├─ "REGIONAL", "1000" g -> ₹"8000" paise ✔
   │  ├─ "REGIONAL", "1001" g -> ₹"10000" paise ✔
   │  ├─ "NATIONAL", "250" g -> ₹"9000" paise ✔
   │  └─ "NATIONAL", "2500" g -> ₹"17000" paise ✔
   ├─ ships free in every zone above 999.00 ✔
   │  ├─ [1] LOCAL ✔
   │  ├─ [2] REGIONAL ✔
   │  └─ [3] NATIONAL ✔
   ├─ rejects zero and negative weights ✔
   │  ├─ 0 g is rejected ✔
   │  ├─ -1 g is rejected ✔
   │  └─ -500 g is rejected ✔
   └─ free shipping starts just above 999.00 ✔
      ├─ [1] one paisa below the limit ✔
      ├─ [2] exactly the limit ✔
      └─ [3] one paisa above the limit ✔

[ 15 tests successful ]
[ 0 tests failed ]

How it works:

  1. A pricing table. The @CsvSource text block reads like the pricing sheet the business wrote. A line starting with # is a comment, so the column names document the table without being parsed as data.
  2. Weight boundaries. Each zone is checked at 500 g and 501 g (or 1,000 g and 1,001 g), where the next 20.00 step begins. (weightInGrams - 1) / 500 puts 500 g in the first step and 501 g in the second.
  3. Every zone. @EnumSource(Zone.class) checks free shipping for all zones, including any added in the future.
  4. Invalid input. @ValueSource supplies zero and negative weights, and the test checks both the exception type and its message.
  5. Named edge cases. @MethodSource with argumentSet covers the free-shipping limit one paisa below, at and above 99_900, with names that explain each case in the report.

Together, four test methods produce fifteen independent tests. The next lesson, Mockito in Java, shows how to test classes whose dependencies, such as a payment gateway, cannot run inside a unit test.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about JUnit Parameterized Tests and get answers drawn from it.

Signed-in readers only.