Java: testing a method with a tiny test runner
A unit test calls one piece of code with known inputs and compares the result with the expected value. Good tests cover a typical value, the boundaries, and the error cases. Real Java projects use a framework such as JUnit, but the idea is the same: arrange, act, assert.
Java
class Main {
static int clamp(int value, int low, int high) {
if (low > high) {
throw new IllegalArgumentException("low > high");
}
return Math.max(low, Math.min(high, value));
}
static int passed = 0;
static int failed = 0;
static void check(String name, int expected, int actual) {
if (expected == actual) {
passed++;
System.out.println("PASS " + name);
} else {
failed++;
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
public static void main(String[] args) {
check("inside range", 5, clamp(5, 0, 10));
check("below range", 0, clamp(-3, 0, 10));
check("above range", 10, clamp(99, 0, 10));
try {
clamp(1, 5, 2);
failed++;
System.out.println("FAIL bad bounds: no exception");
} catch (IllegalArgumentException e) {
passed++;
System.out.println("PASS bad bounds throws: " + e.getMessage());
}
System.out.println(passed + " passed, " + failed + " failed");
}
}