Writing test cases by hand
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Printing five raw numbers with System.out.println forces you to re-check every answer in your head each time you edit your code. A tiny helper method in main compares expected and actual values automatically and highlights failures in one glance.
Normal, boundary, and edge cases: how to pick values systematically
Boundary value analysis means testing right on the edges of the allowed range, just inside, and just outside. The code below shows an off-by-one bug that only an edge value finds.
For example, if a shipping discount applies when an order total is at least 50 and at most 200, testing 100 is a normal case, while 49, 50, 200, and 201 are boundary cases. An off-by-one bug (total > 50 instead of total >= 50) will pass 100 every time and fail only on 50.
Example 1 · Boundary value testing catches a < vs <= bug on range endpoints
public class BoundaryTestDemo { // Rule: free shipping when orderTotal is between 50 and 200 inclusive static boolean buggyFreeShipping(int orderTotal) { return orderTotal > 50 && orderTotal <= 200; // Bug: > 50 instead of >= 50 }
static boolean correctFreeShipping(int orderTotal) { return orderTotal >= 50 && orderTotal <= 200; }
static void check(String label, int total, boolean expected) { boolean actual = buggyFreeShipping(total); String status = (actual == expected) ? "PASS" : "FAIL"; System.out.println(status + " | " + label + " (total=" + total + ")" + " | expected=" + expected + ", actual=" + actual); }
public static void main(String[] args) { check("Normal middle (100)", 100, true); check("Just below lower bound (49)", 49, false); check("Exact lower bound (50)", 50, true); check("Exact upper bound (200)", 200, true); check("Just above upper bound (201)", 201, false); }}PASS | Normal middle (100) (total=100) | expected=true, actual=true PASS | Just below lower bound (49) (total=49) | expected=false, actual=false FAIL | Exact lower bound (50) (total=50) | expected=true, actual=false PASS | Exact upper bound (200) (total=200) | expected=true, actual=true PASS | Just above upper bound (201) (total=201) | expected=false, actual=false
What this code does
- Testing only
100,49, and201would miss the>vs>=mistake completely. - Testing the exact lower boundary (
50) isolates the off-by-one error on the third line.
When constraints say a value or length sits in a range [L, R], boundary value analysis is the habit of testing right on the fences (L and R), just inside the fences (L + 1 and R - 1), and — if invalid inputs are possible — just outside (L - 1 and R + 1).
For arrays and strings, combine value boundaries with structural edge cases: empty (length = 0), single element (length = 1), two elements (length = 2, the smallest input with a pair), all elements equal, and target at index 0 or index n - 1.
- Normal case: comfortably inside the range (e.g.,
100for range[50, 200]). - Boundary cases: exact endpoints and their immediate neighbours (
49,50,200,201). - Structural edge cases:
n = 0,n = 1,n = 2, duplicates, and first/last positions.
Predict the output
Pick the input that finds the bug
Read the code and pick the test input that exposes the problem.
Round 1 of 2
Building a small test harness in main
A test harness is a small helper that runs your solution on a list of inputs and prints PASS or FAIL for each. The code below builds one in six lines, with no library.
Why is a check helper better than raw System.out.println(solve(...)) calls? When you tweak your algorithm and re-run main, you do not want to mentally verify ten lines of numbers again. A harness prints PASS quietly and screams FAIL: expected X but got Y on the exact case you broke.
Example 2 · A reusable main test harness for int and int[] methods
import java.util.Arrays;
public class MiniHarnessDemo { static int failures = 0;
static void checkInt(String name, int actual, int expected) { if (actual == expected) { System.out.println("PASS: " + name); } else { failures++; System.out.println("FAIL: " + name + " -> expected " + expected + " but got " + actual); } }
static void checkArray(String name, int[] actual, int[] expected) { if (Arrays.equals(actual, expected)) { System.out.println("PASS: " + name); } else { failures++; System.out.println("FAIL: " + name + " -> expected " + Arrays.toString(expected) + " but got " + Arrays.toString(actual)); } }
// Method under test: clamp every element to the range [min, max] static int[] clampAll(int[] nums, int min, int max) { int[] out = new int[nums.length]; for (int i = 0; i < nums.length; i++) { out[i] = Math.max(min, Math.min(max, nums[i])); } return out; }
public static void main(String[] args) { checkArray("Normal mix", clampAll(new int[]{-5, 3, 12}, 0, 10), new int[]{0, 3, 10}); checkArray("Boundary values", clampAll(new int[]{0, 10}, 0, 10), new int[]{0, 10}); checkArray("Empty array", clampAll(new int[]{}, 0, 10), new int[]{}); checkInt("Length preserved", clampAll(new int[]{1, 2, 3}, 0, 5).length, 3); System.out.println("Total failures: " + failures); }}PASS: Normal mix PASS: Boundary values PASS: Empty array PASS: Length preserved Total failures: 0
What this code does
checkIntandcheckArraytake less than 20 lines of code and can be pasted into any scratch file or online IDE.Arrays.equalscompares arrays element by element, whileArrays.toStringprints human-readable brackets when a test fails.
A test harness is a small piece of helper code that runs your solution on a list of inputs, compares each result against the expected answer, and prints PASS or FAIL. You do not need any external library to write one — a 6-line check method inside your class is enough.
For array return values, remember that actual == expected in Java compares array references (memory addresses, simplified), not element values, and actual.toString() prints a cryptic string like [I@6d06d69c. Always compare int[] arrays with Arrays.equals(actual, expected) and format them with Arrays.toString(arr).
- Write a static helper
checkInt(String label, int actual, int expected)orcheckArray(String label, int[] actual, int[] expected). - Compare scalars with
==, objects/strings withObjects.equals(actual, expected), and primitive arrays withArrays.equals(actual, expected). - Print
PASSorFAILalong with the test label and bothexpectedandactualvalues. - Keep a static
failurescounter if you want a final summary line at the bottom ofmain.
Watch out for in-place mutation when printing inputs
Many array algorithms modify the input array in place (sorting it, reversing it, or shifting zeroes). If you pass nums into solve(nums) and then print Arrays.toString(nums) in your failure message, you will print the already modified array instead of the original test input!
Example 3 · Preserving the original input string when testing an in-place method
import java.util.Arrays;
public class InPlaceHarnessDemo { static void reverseInPlace(int[] nums) { int left = 0; int right = nums.length - 1; while (left < right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } }
static void testReverse(int[] input, int[] expected) { String before = Arrays.toString(input); // Save before in-place edit! reverseInPlace(input); boolean ok = Arrays.equals(input, expected); System.out.println((ok ? "PASS" : "FAIL") + " | input=" + before + " | expected=" + Arrays.toString(expected) + " | actual=" + Arrays.toString(input)); }
public static void main(String[] args) { testReverse(new int[]{1, 2, 3, 4}, new int[]{4, 3, 2, 1}); testReverse(new int[]{7}, new int[]{7}); testReverse(new int[]{}, new int[]{}); }}PASS | input=[1, 2, 3, 4] | expected=[4, 3, 2, 1] | actual=[4, 3, 2, 1] PASS | input=[7] | expected=[7] | actual=[7] PASS | input=[] | expected=[] | actual=[]
What this code does
- Because
reverseInPlacemutatesinput, we captureString before = Arrays.toString(input)before calling it. - Now the log shows the true input (
[1, 2, 3, 4]) alongside the reversed result ([4, 3, 2, 1]).
To keep failure messages clear, either format String inputStr = Arrays.toString(nums) before calling your method, or pass nums.clone() into the method under test.
Arrays.toString(input) before calling an in-place method so a FAIL line shows the original input that triggered the bug.Next step
Check your understanding
10 quick questions