AdvancedLesson 16 of 206 min read

Testing Your Code: Assertions, Edge Cases and a Failing Test

Learn why tests matter, write a small test harness with real assertions for a price calculator, include edge cases, watch a deliberately broken version fail and see how a test framework fits in.

In this lesson you will

  • Write tests with assertions
  • Choose edge cases
  • Read a failing test
  • Know how JUnit fits

About 28 minutes

The change that broke the discount

Hana changes the weekend price, and a week later a customer complains that the long-rental discount stopped working. Nobody noticed, because nobody checks every rule after every change. Automated tests solve this: small programs that call your code with known inputs and compare the results with the answers you expect. They run in seconds, they never get tired, and they let you change code without fear.

A good test has three parts: arrange the inputs, act by calling the code, and assert that the result is what you expected. The inputs worth testing are the typical case and the edge cases, where mistakes live: zero, one, the boundary of a rule, the largest value and invalid input. For the discount that starts at five days, the interesting rentals are 4, 5 and 6 days. Industry projects use a test framework, for Java most often JUnit, which finds the tests, runs them, reports each failure with its location and integrates with build tools. The ideas below are the same ones a framework automates, and a hand-made harness shows them without needing to download anything.

Part Meaning
Arrange Create the objects and inputs
Act Call the method under test
Assert Compare the actual and the expected result
Edge cases Boundaries, empty and invalid inputs
Regression test A test added for a bug that was found, to keep it fixed
import java.util.*;

class Pricing {
    static final int WEEKDAY = 1200, WEEKEND = 1800;
    static int net(int weekdays, int weekendDays) {
        if (weekdays < 0 || weekendDays < 0) throw new IllegalArgumentException("negative days");
        int gross = weekdays * WEEKDAY + weekendDays * WEEKEND;
        int days = weekdays + weekendDays;
        return days > 5 ? gross - gross / 10 : gross;   // BUG: the rule says 5 or more
    }
}
public class Main {
    static int passed = 0, 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); }
    }
    static void checkThrows(String name, Runnable r) {
        try { r.run(); failed++; System.out.println("FAIL " + name + ": no exception"); }
        catch (IllegalArgumentException e) { passed++; System.out.println("PASS " + name); }
    }
    public static void main(String[] args) {
        check("zero days", 0, Pricing.net(0, 0));
        check("one weekday", 1200, Pricing.net(1, 0));
        check("one weekend day", 1800, Pricing.net(0, 1));
        check("4 days has no discount", 4800, Pricing.net(4, 0));
        check("5 days gets 10% off", 5400, Pricing.net(5, 0));
        check("6 days gets 10% off", 6480, Pricing.net(6, 0));
        check("mixed 3+2 days", 3 * 1200 + 2 * 1800 - (3 * 1200 + 2 * 1800) / 10, Pricing.net(3, 2));
        checkThrows("negative days rejected", () -> Pricing.net(-1, 2));
        System.out.println(passed + " passed, " + failed + " failed");
        System.exit(failed == 0 ? 0 : 1);
    }
}
PASS zero days
PASS one weekday
PASS one weekend day
PASS 4 days has no discount
FAIL 5 days gets 10% off: expected 5400 but was 6000
PASS 6 days gets 10% off
FAIL mixed 3+2 days: expected 6480 but was 7200
PASS negative days rejected
6 passed, 2 failed

The run reported 6 passed and 2 failed, and the process ended with exit code 1, which is how a build system learns that something is wrong. The failures are: “5 days gets 10% off: expected 5400 but was 6000” and “mixed 3+2 days: expected 6480 but was 7200”. The edge case at exactly five days caught the bug, because the code says days > 5 where the rule says five or more. The 6-day test passed, so a test suite that only tried typical long rentals would have missed it entirely, which is why boundaries matter most. The message prints both the expected and the actual value, so the cause is obvious without a debugger: 4800 is what 4 days would cost, and 5 days gave 6000 instead of 5400.

Fixing the bug is a one-character change, from > to >=. After the fix the same tests turn green, and from then on the 5-day test is a regression test that keeps the rule from silently breaking again. A useful habit is to write the failing test first, see it fail for the right reason, fix the code and see it pass. That order proves that the test can actually fail, because a test that cannot fail is worthless.

class Pricing {
    static int net(int weekdays, int weekendDays) {
        if (weekdays < 0 || weekendDays < 0) throw new IllegalArgumentException("negative days");
        int gross = weekdays * 1200 + weekendDays * 1800;
        return (weekdays + weekendDays) >= 5 ? gross - gross / 10 : gross;
    }
}
public class Main {
    public static void main(String[] args) {
        int[][] cases = {{0, 0, 0}, {1, 0, 1200}, {0, 1, 1800}, {4, 0, 4800}, {5, 0, 5400}, {6, 0, 6480}, {3, 2, 6480}};
        int bad = 0;
        for (int[] c : cases) {
            int got = Pricing.net(c[0], c[1]);
            if (got != c[2]) { bad++; System.out.println("FAIL " + c[0] + "+" + c[1] + ": expected " + c[2] + " got " + got); }
        }
        System.out.println(cases.length + " cases, " + bad + " failures");
    }
}
7 cases, 0 failures

After the fix, all 7 cases pass with 0 failures. The last case shows a mixed rental: 3 weekdays and 2 weekend days are 3 x 1200 + 2 x 1800 = 7200 cents before the discount, and since it is 5 days in total the discount of 720 applies, leaving 6480, which is the expected value in the table. Expected values should always come from your own hand calculation or from the written rules, never from running the code under test and copying what it printed, because then the test can only agree with the code, bugs included.

How a framework such as JUnit does it

A framework removes the boilerplate that our harness wrote by hand. In JUnit you annotate methods with @Test, and use methods like assertEquals(expected, actual) and assertThrows. The framework discovers the tests, runs each in isolation, reports every failure with a stack trace, and the build tool runs the whole suite on each change. The JUnit example below was not run here, because the course environment does not include the library, so check the official JUnit documentation for the current version and setup.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class PricingTest {
    @Test void fiveDaysGetsDiscount() {
        assertEquals(5400, Pricing.net(5, 0));
    }
    @Test void negativeDaysRejected() {
        assertThrows(IllegalArgumentException.class, () -> Pricing.net(-1, 2));
    }
}

Check by hand: 5 weekdays are 6000, a tenth is 600, so 5400 is right. 4 days of 1200 are 4800 with no discount. 6 days are 7200 less 720, 6480. These are the numbers in the tests, and they come from the rules and not from the code.

A test that always passes is useless

Make sure each test can fail. Break the code on purpose once and check that the test notices.

Test the boundaries

For every rule that has a threshold, test the value just below, exactly at and just above it. Most bugs hide at the edges.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. The JUnit snippet is shown but was not run in the course environment.

Practice

Write tests for a method that returns the day name for a number from 1 to 7, including 0 and 8. Add a regression test for a bug of your own. Then break your code deliberately and check that at least one test turns red.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What are the three parts of a test?

  1. Arrange, act, assert
  2. Read, write, run
  3. Compile, link, load
  4. Plan, buy, sell

Set up, call, compare.

Which input found the bug?

  1. 100 days
  2. 0 days
  3. A negative number
  4. Exactly 5 days

The boundary of the rule.

Where should expected values come from?

  1. The output of the code under test
  2. A random number
  3. The test name
  4. The written rules or a hand calculation

Otherwise bugs are copied into the test.

What does a non-zero exit code tell a build system?

  1. Everything passed
  2. The file is large
  3. Something failed
  4. The tests are slow

Our harness exited with 1.

What is a regression test?

  1. A test for speed
  2. A test for colours
  3. A test that keeps a fixed bug from returning
  4. A test of the compiler

Add one for every bug.

Summary

  • Tests call code with known inputs and compare to expected answers.
  • Edge cases and boundaries find the most bugs.
  • The failing test showed the bug and the fix turned it green.
  • Expected values come from the rules, not from the code.

Next lesson

Lesson 17 covers concurrency: threads, executors and shared data.

Questions

Do I need JUnit to test?

No, but a framework saves effort and integrates with tools. Start with plain assertions to understand the ideas.

How many tests are enough?

Enough to cover the rules and their boundaries. Quality matters more than count.

What is test-driven development?

Writing a failing test first, then the code that passes it, then tidying up. It is a habit some teams use.

Progress is saved in this browser.