JUnit Parameterized Tests
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
numbersAreEvenfour times, passing2,4,0and-6in 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.paramspackage. Thejunit-jupiterdependency from Java JUnit Basics already includes it.
Note: If your build compiles with the
-parametersflag, 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:
| Attribute | Type |
|---|---|
ints, longs, shorts, bytes | Integer types |
doubles, floats | Floating-point types |
chars, booleans | char, boolean |
strings | String |
classes | Class<?> |
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
nameattribute 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:
| Source | Supplies |
|---|---|
@NullSource | A single null |
@EmptySource | An empty value: "", empty list, set, map or array |
@NullAndEmptySource | Both 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:
@NullAndEmptySourceaddsnulland""before the four@ValueSourcevalues, giving six invocations.- Escape sequences such as
\tand\nare shown escaped in display names, so invisible characters are easy to spot in reports. - Without the
name == nullcheck, thenullcase would fail with aNullPointerException, 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.EXCLUDEgives every constant except the named ones. If someone adds a new status such asRETURNED, it is tested automatically.- Other modes include
MATCH_ALLandMATCH_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 tointautomatically because the parameter is anint. 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:
| Row | Arguments 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 = truetreats the first row as column names and shows them in the report.- The empty
LASTvalue in the second row becomesnull, which tests thelast == nullbranch. - 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 fromsrc/test/resources.numLinesToSkip = 1skips 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 aStream<Arguments>. Eacharguments(...)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 ofStream<Arguments>.
Automatic Argument Conversion
JUnit converts the text values from @ValueSource, @CsvSource and @CsvFileSource to the parameter's type automatically.
| Parameter type | Example 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 aLocalDateand"TUESDAY"into aDayOfWeekwithout 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
105000paise. - For reuse across tests, an
ArgumentsAggregatorwith@AggregateWithcan 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@ParameterizedTestwith 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:
- A pricing table. The
@CsvSourcetext 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. - 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) / 500puts 500 g in the first step and 501 g in the second. - Every zone.
@EnumSource(Zone.class)checks free shipping for all zones, including any added in the future. - Invalid input.
@ValueSourcesupplies zero and negative weights, and the test checks both the exception type and its message. - Named edge cases.
@MethodSourcewithargumentSetcovers the free-shipping limit one paisa below, at and above99_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.