Parameterized and boundary tests
What you will learn
Boundary tests identify where behavior changes. Parameterized tests run one rule with several independent cases, and fixed clocks make time-sensitive rules repeatable.
- Choose success, zero, invalid and overflow boundaries.
- Use parameter sources and a fixed clock.
- Explain timeout limitations and test quality through wrong solutions.
Prerequisite: Java exceptions, interfaces, Maven and Gradle. External framework examples are source-reviewed, NOT RUN; dependency-free examples are tested separately.
Parameterized purchase boundaries
package example.books;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
class BoundaryTest { @ParameterizedTest @CsvSource({"0,250,0", "1,250,250", "3,250,750", "2,17,34", "5,0,0", "2147483647,1,2147483647"}) void totals(int count, int price, int expected) { assertEquals(expected, Receipt.totalCents(count, price)); }
@ParameterizedTest @ValueSource(ints = {-1, -2, Integer.MIN_VALUE}) void negativePrice(int price) { assertThrows(IllegalArgumentException.class, () -> Receipt.totalCents(2, price)); }
@Test void detectsOverflow() { assertThrows(ArithmeticException.class, () -> Receipt.totalCents(Integer.MAX_VALUE, 2)); }}Source-reviewed NOT RUN. Predicted six CSV invocations, three negative-price invocations and one overflow test, all passing on the supplied Receipt.
A small boundary matrix
For nonnegative int operands, test 0, 1, ordinary values, Integer.MAX_VALUE times 1, and overflow. Negative count and negative price are distinct invalid inputs. The expected values come from the contract, not the implementation. A parameterized test with @CsvSource supplies multiple columns; @ValueSource supplies one value per invocation. junit-jupiter includes the parameterized-test dependency; a bare API dependency alone does not provide the engine and parameter sources.
Exceptions and time
Keep invalid cases separate from normal totals. Use assertThrows for the intended exception type and check message or properties only when part of the contract. Inject Clock rather than sleeping until a wall-clock boundary. The deadline example treats equality as expired. assertTimeout executes on the calling thread and reports excessive elapsed time after the executable finishes; it cannot stop a hung action. Preemptive timeouts use another thread and may leave side effects or conflict with thread-local state. @Timeout is a per-test or per-invocation budget, not a hostile-code sandbox. The local fixture runner also has a process deadline.
Test strength
A high-quality suite rejects plausible defects: an always-750 implementation, unchecked overflow, and accepting negative values. A suite should also accept a different correct implementation. A small dependency-free portfolio tests these alternatives against the same cases. No mutation-testing tool or coverage engine is claimed; only the named variants were executed.
Time budget for a finite operation
package example.books;
import org.junit.jupiter.api.Test;import java.time.Duration;import static org.junit.jupiter.api.Assertions.*;
class BudgetTest { @Test void finiteCalculation() { assertTimeout(Duration.ofSeconds(2), () -> assertEquals(34, Receipt.totalCents(2, 17))); }}Source-reviewed NOT RUN. Expected pass under a reasonable runtime; this is not a benchmark and elapsed time is environment dependent.
Fixed clock boundary
import java.time.Clock;import java.time.Instant;import java.time.ZoneOffset;
public class Main { static boolean expired(Instant deadline, Clock clock) { return !clock.instant().isBefore(deadline); } public static void main(String[] args) { Instant now = Instant.parse("2025-01-01T12:00:00Z"); Clock clock = Clock.fixed(now, ZoneOffset.UTC); System.out.println(expired(now.plusSeconds(1), clock)); System.out.println(expired(now, clock)); System.out.println(expired(now.minusSeconds(1), clock)); }}Expected stdout: false, true, true on separate lines. Equality is deliberately expired.
Manual boundary table
public class Main { static int total(int count, int price) { if (count < 0 || price < 0) throw new IllegalArgumentException(); return Math.multiplyExact(count, price); } public static void main(String[] args) { if (total(3, 250) != 750) throw new AssertionError("normal purchase"); if (total(0, 250) != 0) throw new AssertionError("empty purchase"); try { total(-1, 250); throw new AssertionError("negative accepted"); } catch (IllegalArgumentException expected) { } System.out.println("3 checks passed"); }}Expected 3 checks passed; this minimal suite is intentionally weaker than the bundled portfolio. Extend it with independent inputs and overflow checks.
Common mistakes
Do not use the same price and count for every row, calculate expectations using the method under test, or use Thread.sleep as a clock fixture. A timeout is not a guarantee of termination or cleanup.
Practice
Add boundary rows for negative count, zero price, maximum int without overflow and overflow. Predict which rows reject unchecked multiplication and a hardcoded total.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: parameters · assertions · timeouts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parameterized and boundary tests — knowledge check
Testing and debugging knowledge check.
What does each CSV row represent?
Which product must throw ArithmeticException?
Why inject Clock.fixed?
Can assertTimeout stop a hung executable?
What is a useful wrong solution to test?