Essay
Learning Java, Part 17: Testing, Debugging and Documenting
Study notes on unit testing with JUnit 5, choosing test cases, testing exceptions, reading stack traces, using a debugger, writing Javadoc, and the build tools that tie a Java project together. Written entirely by an AI model.
Schildt’s book stops at Part 16. This last part covers the fourth CITS2005 learning outcome, which the book does not: using “software development practices to write, test, debug and document Java programs”. Labs and projects are where it is assessed.
Why automated tests
A test is code that runs your code and checks the result. Once written, it runs in a second, every time you change anything, so a change that breaks something old is caught at once. The Python notes advised testing as you go; in Java the standard tool for this is JUnit.
The idea without a library
Every testing framework does the same thing: call a method with known inputs and compare the result with the expected one. A hand-made version shows there is no magic:
public class MiniTest {
static int passed = 0, failed = 0;
static void check(String name, Object expected, Object actual) {
if (java.util.Objects.equals(expected, actual)) passed++;
else {
failed++;
System.out.println("FAIL " + name + ": expected " + expected + ", got " + actual);
}
}
static int cupsFrom(int ml) {
if (ml < 0) throw new IllegalArgumentException("negative");
return ml / 250;
}
public static void main(String[] args) {
check("exact", 4, cupsFrom(1000));
check("partial cup", 3, cupsFrom(999));
check("zero", 0, cupsFrom(0));
try {
cupsFrom(-1);
check("negative throws", "exception", "no exception");
} catch (IllegalArgumentException e) {
passed++;
}
System.out.println(passed + " passed, " + failed + " failed");
}
}
4 passed, 0 failed
JUnit 5
JUnit replaces check with assertion methods and finds your tests itself. A test class usually mirrors the class under test (Account is tested by AccountTest) and lives in a separate src/test/java folder:
// not run: needs the JUnit 5 library
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AccountTest {
private Account account;
@BeforeEach
void setUp() {
account = new Account("Mei"); // fresh object for every test
account.deposit(5000);
}
@Test
void withdrawReducesBalance() {
assertTrue(account.withdraw(2000));
assertEquals(3000, account.getCents());
}
@Test
void cannotOverdraw() {
assertFalse(account.withdraw(8000));
assertEquals(5000, account.getCents()); // unchanged
}
@Test
void depositRejectsZero() {
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> account.deposit(0));
assertTrue(e.getMessage().contains("positive"));
}
}
@Testmarks a test method. JUnit runs each one on a new instance of the test class, so tests cannot affect each other.@BeforeEachruns before every test;@AfterEach,@BeforeAlland@AfterAllalso exist.- The main assertions are
assertEquals(expected, actual)(expected first, so failure messages read correctly),assertTrue,assertFalse,assertNull,assertNotNull,assertSameandassertThrows. Compare doubles with a tolerance:assertEquals(0.3, x, 1e-9). assertThrowstakes a lambda (Part 14) and returns the exception, so you can check its message.@ParameterizedTestwith@ValueSourceor@CsvSourceruns one test for many inputs.
The Account class here is the one from Part 6.
Choosing test cases
The most useful tests sit at the edges:
- typical values, and the boundaries on each side of every condition (
mark49, 50 and 51 for a pass at 50); - empty and single-item inputs: an empty array, a string of length one, a list with one element;
- invalid input:
null, negative numbers, values that should throw; - for objects, sequences of calls, not just single calls: deposit, then withdraw, then check.
Writing the test before the code (test-driven development) forces you to decide what the method should do before you think about how.
Debugging
Read the stack trace
Part 9 showed the shape: the exception and message on the first line, then at lines from the innermost call outwards. Find the first at line that is in your code; that is usually where to look. “Caused by:” sections lower down give the original exception in a chain.
Common exceptions and their usual cause:
| Exception | Usual cause |
|---|---|
NullPointerException |
a field or variable was never assigned; the message names which |
ArrayIndexOutOfBoundsException |
an off-by-one loop bound: <= instead of < |
ClassCastException |
a downcast without an instanceof check |
ConcurrentModificationException |
changing a collection while looping over it |
NumberFormatException |
parsing text with spaces or a decimal point as an int |
StackOverflowError |
recursion without a reachable base case |
Use a debugger
Printing values works, but a debugger is faster once you know it. In IntelliJ IDEA or VS Code:
- Set a breakpoint by clicking beside a line, then run in debug mode. The program stops there.
- Step over runs the current line; step into enters the method it calls; step out finishes the current method.
- The variables panel shows every local and field. A conditional breakpoint stops only when, say,
i == 99. - The JDK also includes a command-line debugger,
jdb, which is enough when there is no IDE.
Debug by forming a guess about what is wrong and checking it, rather than changing lines at random. When you find the bug, write a test that would have caught it.
Documenting with Javadoc
A Javadoc comment starts with /** and sits immediately before a class, method or field. The javadoc tool, which comes with the JDK, turns these comments into HTML pages like the official Java API documentation.
/**
* A kettle that holds a limited amount of water.
*/
public class Kettle {
private final int capacityMl;
private int waterMl;
/**
* Creates an empty kettle.
*
* @param capacityMl the most water the kettle can hold, in millilitres; must be positive
* @throws IllegalArgumentException if {@code capacityMl} is not positive
*/
public Kettle(int capacityMl) {
if (capacityMl <= 0) throw new IllegalArgumentException("capacity must be positive");
this.capacityMl = capacityMl;
}
/**
* Adds water, stopping at the kettle's capacity.
*
* @param ml the amount to add, in millilitres
* @return the amount that did not fit and was spilled
*/
public int fill(int ml) {
int room = capacityMl - waterMl;
int added = Math.min(room, ml);
waterMl += added;
return ml - added;
}
public static void main(String[] args) {
Kettle k = new Kettle(1700);
System.out.println(k.fill(1000) + " " + k.fill(1000));
}
}
0 300
Run javadoc -d docs Kettle.java to generate the pages. The tags to know are @param, @return, @throws, @see and {@code ...}. Document what a method does, its inputs, its result and its failures, so a caller never needs to read the body. Explain why with ordinary // comments inside the code.
Build tools
Real projects don’t run javac by hand. Maven (pom.xml) and Gradle (build.gradle) download libraries such as JUnit and JavaFX, compile the code, run the tests and package the result, all from one command (mvn test, gradle test). They both expect the same layout: src/main/java for code and src/test/java for tests. Your labs may provide a build file; reading it is part of knowing the project.
Version control with git belongs to the same toolkit: commit small working steps, so you can always go back to the last version that passed its tests.
Looking back
The series has gone from javac to threads, generics and GUIs. A few habits carry across all of it:
- Let the compiler help: declare precise types, write
@Override, and read the first error first. - Keep fields
privateand give each class one job. - Compare objects with
equals, and overridehashCodewith it. - Catch the specific exception you expect, and close resources with try-with-resources.
- Share as little mutable data between threads as possible, and lock what you do share.
- Program to interfaces, and test at the edges.
Exam-style checks
- Write two JUnit tests for a method that returns the larger of two
ints, including one boundary case. - Why does JUnit create a new test-class instance for each test?
- How would you test that a method throws an exception?
- What is the difference between a Javadoc comment and an ordinary comment? Name three Javadoc tags.
Where to practise
Go back to the classes you wrote in earlier parts (the queue, the bank account, the generic stack) and give each a JUnit test class with at least one test per method and one per edge case. Add Javadoc to their public methods and generate the HTML. Then introduce a deliberate off-by-one bug, and find it with the debugger rather than with print statements.