Lesson 2 of 5 · 11 min · Unit testing in Java

Edge cases, boundaries and parameterized tests

Covers: JUnit 6 (Jupiter) and AssertJ on Java 17 or newer. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • Choose test cases using boundary values and equivalence classes
  • Always consider null, empty, zero, negative and very large inputs
  • Write parameterized tests with @ValueSource, @CsvSource and @MethodSource
  • Group related tests with @Nested and @DisplayName
  • Make code that uses time or randomness testable

In simple words

Most bugs do not hide in the ordinary case; they hide at the edges. A shop discount works for 10 percent but breaks at 0, at 100, at "minus 5" or when the price is empty. Testing edge cases means deliberately trying the awkward inputs, the first and last valid values and the just-invalid ones, because that is where programs usually slip.

Words to know

  • Edge case: an unusual or extreme input that tests the limits of the code.
  • Boundary value: a value at the border between valid and invalid, such as 0 and 100 for a percentage.
  • Equivalence class: a group of inputs the code should treat the same way.
  • Parameterized test: one test method that runs many times with different inputs.

Where bugs hide

Think of what could be different from the "happy path":

Kind Examples
Boundaries 0, 1, max, max + 1, -1, exactly at a limit, one below, one above
Empty or missing null, "", " ", empty list, empty map, no rows
Size one element, two elements, very large collections
Duplicates and order repeated values, unsorted input, ties
Text Unicode, accents, Indian scripts, very long strings, leading and trailing spaces, mixed case
Numbers zero, negative, decimals, overflow, NaN, rounding (0.1 + 0.2)
Dates and time leap day, end of month, daylight saving (not in India but in others), time zones, midnight, year boundaries
State and order calling twice, calling in the wrong order, concurrent use
Failure a dependency throws, a timeout, a file is missing

Use equivalence classes to avoid testing every value: for discounted(price, percent) with a valid range 0 to 100, there are three classes (below 0, 0 to 100, above 100), and you test one or two values from each plus the boundaries (-1, 0, 1, 99, 100, 101).

Boundary tests in practice

class PriceCalculatorTest {

    private final PriceCalculator calc = new PriceCalculator();

    @Test void zeroPercentKeepsPrice()              { assertEquals(1000, calc.discounted(1000, 0), 0.001); }
    @Test void hundredPercentMakesItFree()          { assertEquals(0, calc.discounted(1000, 100), 0.001); }
    @Test void oneAbove100IsRejected()              { assertThrows(IllegalArgumentException.class, () -> calc.discounted(1000, 101)); }
    @Test void oneBelowZeroIsRejected()             { assertThrows(IllegalArgumentException.class, () -> calc.discounted(1000, -1)); }
    @Test void zeroPriceStaysZero()                 { assertEquals(0, calc.discounted(0, 50), 0.001); }
    @Test void negativePriceIsRejected()            { assertThrows(IllegalArgumentException.class, () -> calc.discounted(-0.01, 10)); }
}

Six tests that read like a specification. They would catch the classic off-by-one bug percent >= 100 instead of percent > 100.

Parameterized tests

Several tests that differ only in their data are repetitive. A parameterized test runs one method with many inputs (add junit-jupiter-params, included in the junit-jupiter aggregate artifact and in Spring Boot's test starter).

@ParameterizedTest
@ValueSource(ints = {-1, 101, 1000, Integer.MIN_VALUE})
void invalidPercentsAreRejected(int percent) {
    assertThrows(IllegalArgumentException.class, () -> calc.discounted(100, percent));
}

@ParameterizedTest(name = "{0} with {1}% off is {2}")
@CsvSource({
    "1000, 10, 900",
    "1000,  0, 1000",
    "1000, 100, 0",
    "250.50, 50, 125.25"
})
void discountedValues(double price, int percent, double expected) {
    assertEquals(expected, calc.discounted(price, percent), 0.001);
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"  ", "\t", "\n"})
void blankNamesAreRejected(String name) {
    assertThrows(IllegalArgumentException.class, () -> new Customer(name, "a@b.com"));
}

Sources:

Source Use
@ValueSource a single argument from literals (ints, strings, doubles)
@NullSource, @EmptySource, @NullAndEmptySource null and empty values
@CsvSource several arguments per row (text blocks work too), @CsvFileSource for a file
@EnumSource every value of an enum
@MethodSource("name") a static method returning a stream of arguments (complex objects)
static Stream<Arguments> cartCases() {
    return Stream.of(
        arguments(List.of(), 0.0),
        arguments(List.of(new Item("pen", 40)), 40.0),
        arguments(List.of(new Item("pen", 40), new Item("book", 120)), 160.0));
}

@ParameterizedTest
@MethodSource("cartCases")
void cartTotals(List<Item> items, double expectedTotal) {
    assertEquals(expectedTotal, new Cart(items).total(), 0.001);
}

The name pattern in @ParameterizedTest(name = ...) makes the test report readable (1000 with 10% off is 900). Each row is reported as its own test, so one failing row does not hide others.

Testing exceptions and error messages

Test the error path as seriously as the happy path:

@Test
void withdrawMoreThanBalanceFailsAndKeepsBalance() {
    Account account = new Account(100);

    assertThatThrownBy(() -> account.withdraw(150))
            .isInstanceOf(InsufficientFundsException.class)
            .hasMessageContaining("150");

    assertThat(account.balance()).isEqualTo(100);        // the failure left the state unchanged
}

Check what the failing call did not change (no money moved, nothing saved).

Grouping with @Nested

For a class with many behaviours, group tests with @Nested inner classes and @DisplayName, which keeps reports tidy and allows a shared setup per group:

@DisplayName("Cart")
class CartTest {

    @Nested @DisplayName("when empty")
    class WhenEmpty {
        private final Cart cart = new Cart();

        @Test void totalIsZero()      { assertEquals(0, cart.total(), 0.001); }
        @Test void checkoutIsRejected() { assertThrows(IllegalStateException.class, cart::checkout); }
    }

    @Nested @DisplayName("with two items")
    class WithTwoItems {
        private Cart cart;

        @BeforeEach void setUp() {
            cart = new Cart();
            cart.add(new Item("pen", 40));
            cart.add(new Item("book", 120));
        }

        @Test void totalIsTheSum()    { assertEquals(160, cart.total(), 0.001); }
        @Test void removingOneUpdatesTotal() {
            cart.remove("pen");
            assertEquals(120, cart.total(), 0.001);
        }
    }
}

Time, randomness and other hidden inputs

Code that calls LocalDate.now(), Instant.now(), Math.random() or UUID.randomUUID() is hard to test, because the result changes every run. Make these inputs to the code (dependency injection again):

public class CouponService {
    private final Clock clock;
    public CouponService(Clock clock) { this.clock = clock; }

    public boolean isValid(Coupon c) {
        return !LocalDate.now(clock).isAfter(c.expiresOn());
    }
}

@Test
void couponIsValidOnItsLastDay() {
    Clock fixed = Clock.fixed(Instant.parse("2025-10-31T10:00:00Z"), ZoneId.of("Asia/Kolkata"));
    var service = new CouponService(fixed);
    assertTrue(service.isValid(new Coupon("DIWALI", LocalDate.of(2025, 10, 31))));
}

Pass a fixed Clock in tests (and Clock.systemUTC() or systemDefaultZone() in production, as a Spring bean). Do the same for random generators (inject a Random with a seed) and ID generators. Avoid Thread.sleep in tests: it makes them slow and flaky; use a fake clock, Awaitility for asynchronous results, or restructure the code.

Property-style thinking

Beyond examples, ask for properties that must always hold: the discounted price is never negative and never above the original; sorting twice gives the same result; encoding then decoding returns the original. Libraries such as jqwik generate hundreds of random inputs and shrink failing ones to a minimal example. Even without a library, a loop over many generated values with a property check can find surprising bugs.

When a test is hard to write

If you cannot test a class without many mocks, a real database or a static call, the design is telling you something: too many responsibilities, hidden dependencies, global state. Fixing the design (extract a class, inject the dependency, make the logic a pure function) makes testing easy, and the code better.

Common mistakes

  • Only testing the happy path.
  • Not testing boundaries, so off-by-one errors escape.
  • Skipping null and empty inputs.
  • Copy-pasting ten similar tests instead of a parameterized one.
  • Testing code that reads the real clock or random numbers.
  • Thread.sleep in tests.
  • Checking only that an exception occurred, not that state stayed consistent.

Try it yourself

  1. List the equivalence classes and boundaries for a function that grades marks (below 40 fail, 40 to 59 pass, 60 to 74 second class, 75 and above distinction). Write the tests with @CsvSource.
  2. Write @NullAndEmptySource tests for a method that parses a name.
  3. Group the tests for a Cart class into @Nested classes for empty and non-empty carts.
  4. Refactor a method that uses LocalDate.now() to take a Clock, and test the last-day-of-month and leap-day cases.
  5. Write a property test by hand: for 1,000 random prices and percents, the result is between 0 and the price.

Check yourself

What is a boundary value, and why test it?

A value at the edge between valid and invalid input, such as 0 and 100 for a percentage; bugs such as off-by-one errors occur at the boundaries.

What is a parameterized test?

A single test method that runs repeatedly with different arguments from a source such as @CsvSource or @MethodSource, reported as separate tests.

How do you test code that depends on the current date?

Inject a Clock into the class and pass Clock.fixed(...) in tests, so the date is controlled.

Why check state after an expected exception?

To ensure the failed operation left the object unchanged, for example no money was withdrawn.

Interview questions

How do you decide which test cases to write?

Use equivalence classes to cover each kind of input once, add boundary values at their edges, include null, empty, zero and negative inputs, error paths and any bugs found before, and prefer behaviours over lines of code.

What is the difference between @ValueSource and @CsvSource?

@ValueSource supplies a single argument per invocation from literals; @CsvSource supplies several arguments per row, for tests with an input and an expected output.

How do you make time-dependent code testable?

Inject a Clock (or a time provider) instead of calling now() directly, and use a fixed or controllable clock in tests.

Summary

  • Bugs cluster at boundaries and unusual inputs: use equivalence classes, boundary values, null, empty and error cases.
  • Parameterized tests (@ValueSource, @CsvSource, @MethodSource) remove repetition.
  • @Nested and @DisplayName organise tests; check state after failures.
  • Inject clocks and random sources so tests are deterministic; hard-to-test code points to design problems.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Unit testing in Java with JUnit and Mockito for Java Full Stack Developer and scores every answer, with what to fix.