Java Test a Contract Instead of a Happy Path Only
A useful test checks the boundary of a promise, including cases that might expose an off-by-one or overflow error. Assertions can help during development, but public input validation must not depend on them being enabled.
Understand the idea
Java’s assert statements are normally disabled unless assertions are enabled for the relevant code. Use ordinary checks and exceptions for required validation. For a repeatable example, an explicit check helper can throw AssertionError on a wrong result and run without an external testing framework. Larger projects often use a test framework, but the quality of the chosen cases matters more than the amount of test syntax.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
static int remaining(int capacity, int booked) {
if (capacity < 0 || booked < 0 || booked > capacity) throw new IllegalArgumentException("invalid counts");
return capacity - booked;
}
static void check(boolean condition) { if (!condition) throw new AssertionError("wrong remaining seats"); }
public static void main(String[] args) {
check(remaining(8, 0) == 8);
check(remaining(8, 8) == 0);
try {
remaining(8, 9);
throw new AssertionError("overbooking was accepted");
} catch (IllegalArgumentException expected) {
System.out.println("Boundary checks passed");
}
}
}
Expected output
Boundary checks passedThe tests cover an empty room, a full room and an invalid overbooking. The final catch treats only the expected rejection as a passing case. A different exception or a silently accepted overbooking still fails the program, which prevents the test from masking an unrelated defect.
Check the official Java documentation for detailed contracts and supported options.