×

java · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A proves one small piece works.

Professionals do not hope their code works; they prove it. A unit test runs one small piece, a single method, on input whose answer you already know, and compares. Run every test after each change and you find out within seconds when something breaks.

Big frameworks like JUnit exist, but the heart of each is an : this value must equal that one. A tiny check(name, actual, expected) method that prints PASS or FAIL does the same job here.

Test the edge cases hardest: empty text, zero, a negative number, the biggest value allowed. For bad input, test that the method throws, by catching the exception inside the test.

public class Main {
    static void check(String name, Object actual, Object expected) {
        if (actual.equals(expected)) {
            System.out.println("PASS " + name);
        } else {
            System.out.println("FAIL " + name + ": got " + actual + ", expected " + expected);
        }
    }
    static String initials(String fullName) {
        StringBuilder result = new StringBuilder();
        for (String part : fullName.trim().split(" ")) {
            if (!part.isEmpty()) {
                result.append(part.substring(0, 1).toUpperCase());
            }
        }
        return result.toString();
    }
    public static void main(String[] args) {
        check("two names", initials("ada lovelace"), "AL");
        check("extra spaces", initials("  grace   hopper "), "GH");
        check("empty", initials(""), "");
    }
}

Each test has a name that says what it proves, so a FAIL line tells you where to look.