Skip to content

Project Tests

The Course
•
15 min study

A multi-file application needs checks across boundaries as well as checks of small methods. The capstone's TrackerTest uses the actual repository, parser and service. It avoids a test framework so the same tests run in the browser and in a local JDK.

Work through the example

Start with a test whose result you can inspect independently. A set's duplicate rejection is visible in both its boolean result and its size. The method under test must not calculate its own expected answer. For the project, fixed examples prove ordering, accepted counts and preservation after rejected updates.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.Set;
import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        Set<String> ids = new LinkedHashSet<>();
        ids.add("A1");
        boolean addedAgain = ids.add("A1");
        check("duplicate not added", !addedAgain);
        check("one id", ids.size() == 1);
        System.out.println("Set checks passed");
    }

    static void check(String label, boolean condition) {
        if (!condition) {
            throw new AssertionError(label);
        }
    }
}
Check your prediction
Text
Set checks passed

Compare the behavior

A snapshot test must change one side after copying. Checking that a newly created copy initially equals its source would also pass for an alias. Here clearing the copy distinguishes the required behavior from a reference leak.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("A1");
        List<String> snapshot = new ArrayList<>(source);
        snapshot.clear();
        if (source.size() != 1) {
            throw new AssertionError("snapshot exposed source");
        }
        System.out.println("Ownership check passed");
    }
}
Check your prediction
Text
Ownership check passed

Run the complete project

Read the source tabs in this order: Status, Timed, Task, TaskRepository, MemoryTaskRepository, TaskParser, ImportResult, Reports, TaskService, then Main or TrackerTest. The marked entry is TrackerTest.java. Other files are compiled with it, not executed independently. Keep the filenames and public class names aligned.

Run the project checks Java
import java.util.ArrayList; import java.util.List; public final class ImportResult { private final int accepted; private final List<String> errors; public ImportResult(int accepted, List<String> errors) { this.accepted = accepted; this.errors = new ArrayList<>(errors); } public int accepted() { return accepted; } public List<String> errors() { return new ArrayList<>(errors); } } public class Main { public static void main(String[] args) { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); String[] lines = { "B2;Practice loops;20;TODO", "bad record", "A1;Read chapter;25;TODO", "A1;Duplicate;10;TODO", "C3;Write tests;20;TODO" }; ImportResult result = service.importLines(lines); System.out.println("Accepted: " + result.accepted()); System.out.println("Rejected: " + result.errors().size()); service.complete("B2"); for (Task task : service.openOrdered()) { System.out.println(task.id() + ": " + task.title() + " (" + task.minutes() + ")"); } System.out.println("Open minutes: " + service.openMinutes()); Task longest = Reports.longest(service.openOrdered()); System.out.println("Longest open: " + longest.id()); } } import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class MemoryTaskRepository implements TaskRepository { private final Map<String, Task> tasks = new LinkedHashMap<>(); @Override public void add(Task task) { if (task == null || tasks.containsKey(task.id())) { throw new IllegalArgumentException("duplicate or missing task"); } tasks.put(task.id(), task); } @Override public Task find(String id) { return tasks.get(id); } @Override public void replace(Task task) { if (task == null || !tasks.containsKey(task.id())) { throw new IllegalArgumentException("existing task required"); } tasks.put(task.id(), task); } @Override public List<Task> all() { return new ArrayList<>(tasks.values()); } } import java.util.List; /** Generic reports that work for any Timed values, not only Task. */ public final class Reports { private Reports() { } /** Reads only, so it accepts a list of any Timed subtype: List<Task> included. */ public static int totalMinutes(List<? extends Timed> items) { int total = 0; for (Timed item : items) { total += item.minutes(); } return total; } /** Returns the caller's own element type, or null for an empty list. Ties keep the first. */ public static <T extends Timed> T longest(List<T> items) { T best = null; for (T item : items) { if (best == null || item.minutes() > best.minutes()) { best = item; } } return best; } } public enum Status { TODO, DONE } /** Immutable task: copies of collections can safely share these values. */ public final class Task implements Timed { private final String id; private final String title; private final int minutes; private final Status status; public Task(String id, String title, int minutes, Status status) { if (id == null || id.trim().isEmpty() || id.contains(";")) { throw new IllegalArgumentException("valid id required"); } if (title == null || title.trim().isEmpty() || title.contains(";")) { throw new IllegalArgumentException("valid title required"); } if (minutes < 1 || minutes > 240 || status == null) { throw new IllegalArgumentException("valid minutes and status required"); } this.id = id.trim(); this.title = title.trim(); this.minutes = minutes; this.status = status; } public String id() { return id; } public String title() { return title; } @Override public int minutes() { return minutes; } public Status status() { return status; } public Task withStatus(Status next) { return new Task(id, title, minutes, next); } } /** A small four-field format, deliberately not general CSV. */ public final class TaskParser { public Task parse(String line) { if (line == null) { throw new IllegalArgumentException("line required"); } String[] fields = line.split(";", -1); if (fields.length != 4) { throw new IllegalArgumentException("expected id;title;minutes;status"); } int minutes = Integer.parseInt(fields[2].trim()); Status status = Status.valueOf(fields[3].trim()); return new Task(fields[0], fields[1], minutes, status); } } import java.util.List; /** Duplicate adds and missing replacements reject before changing state. */ public interface TaskRepository { void add(Task task); Task find(String id); // Null means absent; null tasks are never stored. void replace(Task task); List<Task> all(); // A separate container in insertion order. } import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public final class TaskService { private final TaskRepository repository; private final TaskParser parser; public TaskService(TaskRepository repository, TaskParser parser) { if (repository == null || parser == null) { throw new IllegalArgumentException("dependencies required"); } this.repository = repository; this.parser = parser; } /** * Read records until EOF. Skip blanks; report rejected records with their * physical line number; retain successful records. The caller owns the * reader: this method neither closes it nor hides a read failure. */ public ImportResult importFrom(BufferedReader reader) throws IOException { List<String> errors = new ArrayList<>(); int accepted = 0; int lineNumber = 0; String line = reader.readLine(); while (line != null) { lineNumber++; if (!line.trim().isEmpty()) { try { repository.add(parser.parse(line)); accepted++; } catch (IllegalArgumentException error) { errors.add("Line " + lineNumber + ": " + error.getMessage()); } } line = reader.readLine(); } return new ImportResult(accepted, errors); } /** Convenience for in-memory records: one array element per line. */ public ImportResult importLines(String[] lines) { ImportResult result; try (BufferedReader reader = new BufferedReader(new StringReader(String.join("\n", lines)))) { result = importFrom(reader); } catch (IOException error) { throw new IllegalStateException("reading records failed", error); } return result; } /** Repeating completion is harmless. A missing ID returns false. */ public boolean complete(String id) { Task task = repository.find(id); if (task == null) { return false; } repository.replace(task.withStatus(Status.DONE)); return true; } public List<Task> openOrdered() { Comparator<Task> byMinutes = Comparator.comparingInt(Task::minutes); return repository.all().stream() .filter(task -> task.status() == Status.TODO) .sorted(byMinutes.thenComparing(Task::id)) .toList(); } public int openMinutes() { return Reports.totalMinutes(openOrdered()); } } /** Anything with a duration in minutes. Task implements it; so could a future Session. */ public interface Timed { int minutes(); } import java.util.List; /** No test library required; every failed expectation throws AssertionError. */ public class TrackerTest { public static void main(String[] args) { testValidationAndParser(); testRepository(); testImportRecovery(); testOrderingAndCompletion(); testReports(); System.out.println("All tracker checks passed"); } static void testValidationAndParser() { TaskParser parser = new TaskParser(); Task task = parser.parse(" A1 ; Read ; 1 ; TODO "); check("normalized id", task.id().equals("A1")); check("normalized title", task.title().equals("Read")); check("minimum minutes", task.minutes() == 1); check("maximum minutes", parser.parse("A;Read;240;DONE").minutes() == 240); for (String line : new String[] { "A;Read;0;TODO", "A;Read;241;TODO", "A;Read;nope;TODO", "A;Read;25;", "A;Read;25;todo", "A;;25;TODO", ";Read;25;TODO", "A;Read;25;TODO;extra" }) { try { parser.parse(line); throw new AssertionError("accepted invalid line: " + line); } catch (IllegalArgumentException expected) { // Only a documented input rejection counts as passing. } } } static void testRepository() { TaskRepository repository = new MemoryTaskRepository(); Task original = new Task("A1", "Read", 25, Status.TODO); repository.add(original); try { repository.add(new Task("A1", "Lost", 10, Status.DONE)); throw new AssertionError("duplicate accepted"); } catch (IllegalArgumentException expected) { check("duplicate kept original", repository.find("A1") == original); } List<Task> snapshot = repository.all(); snapshot.clear(); check("snapshot cannot clear store", repository.all().size() == 1); check("missing lookup", repository.find("missing") == null); try { repository.replace(new Task("missing", "Other", 10, Status.TODO)); throw new AssertionError("missing replacement accepted"); } catch (IllegalArgumentException expected) { check("missing replace leaves store", repository.all().size() == 1); } } static void testImportRecovery() { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); ImportResult result = service.importLines(new String[] { "A1;Read;25;TODO", "bad", " ", "A1;Lost;10;TODO", "B2;Test;10;TODO" }); check("accepted count", result.accepted() == 2); check("rejected count", result.errors().size() == 2); check("physical line number", result.errors().get(1).startsWith("Line 4:")); check("good line after rejection", repository.find("B2") != null); check("duplicate not overwritten", repository.find("A1").title().equals("Read")); result.errors().clear(); check("error snapshot isolated", result.errors().size() == 2); check("empty batch", service.importLines(new String[0]).accepted() == 0); } static void testOrderingAndCompletion() { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); service.importLines(new String[] { "B;Second;20;TODO", "A;First;20;TODO", "C;Long;30;TODO" }); check("tie broken by id", service.openOrdered().get(0).id().equals("A")); check("primary sort", service.openOrdered().get(2).id().equals("C")); check("sum open", service.openMinutes() == 70); Task before = repository.find("A"); check("complete existing", service.complete("A")); check("original immutable", before.status() == Status.TODO); check("new state", repository.find("A").status() == Status.DONE); check("completed excluded", service.openMinutes() == 50); check("complete repeated", service.complete("A")); check("repeat has same effect", service.openMinutes() == 50); check("missing completion", !service.complete("missing")); check("missing no new task", repository.all().size() == 3); } static void testReports() { List<Task> tasks = List.of( new Task("A", "Short", 10, Status.TODO), new Task("B", "Long", 30, Status.TODO), new Task("C", "Also long", 30, Status.TODO)); check("total of a List<Task>", Reports.totalMinutes(tasks) == 70); check("empty total", Reports.totalMinutes(List.of()) == 0); Task longest = Reports.longest(tasks); check("longest keeps Task type and first of a tie", longest.id().equals("B")); check("longest of empty", Reports.longest(List.<Task>of()) == null); } static void check(String name, boolean condition) { if (!condition) { throw new AssertionError(name); } } }
Check your prediction
Text
All tracker checks passed

The source is also available in the task-tracker download. Each editor on the site owns its own file set; an edit in one editor doesn't change another. To test your changes, make them in the editor whose entry is TrackerTest.java, or download the project and run both entries locally.

Practice with the project tests

Exercise

Project Tests: protect reader ownership

TaskService.importFrom promises that the caller owns the reader: it reads to the end but does not close it. Nothing in TrackerTest checks that yet. In the workspace below (entry TrackerTest.java):

  1. Add a testReaderStaysOpen() method and call it from main. It should import one valid line from a reader you create, check that one task was accepted, and then check that the reader is still usable: readLine() returns null at the end of input, but throws IOException if the reader was closed. Run it: All tracker checks passed.
  2. Prove the test can fail. In TaskService.java, add reader.close(); just before importFrom's return statement and run again. Your test, and only your test, should fail with a clear message. Remove the line again.
Your workspace: project and tests Java
import java.util.ArrayList; import java.util.List; public final class ImportResult { private final int accepted; private final List<String> errors; public ImportResult(int accepted, List<String> errors) { this.accepted = accepted; this.errors = new ArrayList<>(errors); } public int accepted() { return accepted; } public List<String> errors() { return new ArrayList<>(errors); } } public class Main { public static void main(String[] args) { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); String[] lines = { "B2;Practice loops;20;TODO", "bad record", "A1;Read chapter;25;TODO", "A1;Duplicate;10;TODO", "C3;Write tests;20;TODO" }; ImportResult result = service.importLines(lines); System.out.println("Accepted: " + result.accepted()); System.out.println("Rejected: " + result.errors().size()); service.complete("B2"); for (Task task : service.openOrdered()) { System.out.println(task.id() + ": " + task.title() + " (" + task.minutes() + ")"); } System.out.println("Open minutes: " + service.openMinutes()); Task longest = Reports.longest(service.openOrdered()); System.out.println("Longest open: " + longest.id()); } } import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class MemoryTaskRepository implements TaskRepository { private final Map<String, Task> tasks = new LinkedHashMap<>(); @Override public void add(Task task) { if (task == null || tasks.containsKey(task.id())) { throw new IllegalArgumentException("duplicate or missing task"); } tasks.put(task.id(), task); } @Override public Task find(String id) { return tasks.get(id); } @Override public void replace(Task task) { if (task == null || !tasks.containsKey(task.id())) { throw new IllegalArgumentException("existing task required"); } tasks.put(task.id(), task); } @Override public List<Task> all() { return new ArrayList<>(tasks.values()); } } import java.util.List; /** Generic reports that work for any Timed values, not only Task. */ public final class Reports { private Reports() { } /** Reads only, so it accepts a list of any Timed subtype: List<Task> included. */ public static int totalMinutes(List<? extends Timed> items) { int total = 0; for (Timed item : items) { total += item.minutes(); } return total; } /** Returns the caller's own element type, or null for an empty list. Ties keep the first. */ public static <T extends Timed> T longest(List<T> items) { T best = null; for (T item : items) { if (best == null || item.minutes() > best.minutes()) { best = item; } } return best; } } public enum Status { TODO, DONE } /** Immutable task: copies of collections can safely share these values. */ public final class Task implements Timed { private final String id; private final String title; private final int minutes; private final Status status; public Task(String id, String title, int minutes, Status status) { if (id == null || id.trim().isEmpty() || id.contains(";")) { throw new IllegalArgumentException("valid id required"); } if (title == null || title.trim().isEmpty() || title.contains(";")) { throw new IllegalArgumentException("valid title required"); } if (minutes < 1 || minutes > 240 || status == null) { throw new IllegalArgumentException("valid minutes and status required"); } this.id = id.trim(); this.title = title.trim(); this.minutes = minutes; this.status = status; } public String id() { return id; } public String title() { return title; } @Override public int minutes() { return minutes; } public Status status() { return status; } public Task withStatus(Status next) { return new Task(id, title, minutes, next); } } /** A small four-field format, deliberately not general CSV. */ public final class TaskParser { public Task parse(String line) { if (line == null) { throw new IllegalArgumentException("line required"); } String[] fields = line.split(";", -1); if (fields.length != 4) { throw new IllegalArgumentException("expected id;title;minutes;status"); } int minutes = Integer.parseInt(fields[2].trim()); Status status = Status.valueOf(fields[3].trim()); return new Task(fields[0], fields[1], minutes, status); } } import java.util.List; /** Duplicate adds and missing replacements reject before changing state. */ public interface TaskRepository { void add(Task task); Task find(String id); // Null means absent; null tasks are never stored. void replace(Task task); List<Task> all(); // A separate container in insertion order. } import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public final class TaskService { private final TaskRepository repository; private final TaskParser parser; public TaskService(TaskRepository repository, TaskParser parser) { if (repository == null || parser == null) { throw new IllegalArgumentException("dependencies required"); } this.repository = repository; this.parser = parser; } /** * Read records until EOF. Skip blanks; report rejected records with their * physical line number; retain successful records. The caller owns the * reader: this method neither closes it nor hides a read failure. */ public ImportResult importFrom(BufferedReader reader) throws IOException { List<String> errors = new ArrayList<>(); int accepted = 0; int lineNumber = 0; String line = reader.readLine(); while (line != null) { lineNumber++; if (!line.trim().isEmpty()) { try { repository.add(parser.parse(line)); accepted++; } catch (IllegalArgumentException error) { errors.add("Line " + lineNumber + ": " + error.getMessage()); } } line = reader.readLine(); } return new ImportResult(accepted, errors); } /** Convenience for in-memory records: one array element per line. */ public ImportResult importLines(String[] lines) { ImportResult result; try (BufferedReader reader = new BufferedReader(new StringReader(String.join("\n", lines)))) { result = importFrom(reader); } catch (IOException error) { throw new IllegalStateException("reading records failed", error); } return result; } /** Repeating completion is harmless. A missing ID returns false. */ public boolean complete(String id) { Task task = repository.find(id); if (task == null) { return false; } repository.replace(task.withStatus(Status.DONE)); return true; } public List<Task> openOrdered() { Comparator<Task> byMinutes = Comparator.comparingInt(Task::minutes); return repository.all().stream() .filter(task -> task.status() == Status.TODO) .sorted(byMinutes.thenComparing(Task::id)) .toList(); } public int openMinutes() { return Reports.totalMinutes(openOrdered()); } } /** Anything with a duration in minutes. Task implements it; so could a future Session. */ public interface Timed { int minutes(); } import java.util.List; /** No test library required; every failed expectation throws AssertionError. */ public class TrackerTest { public static void main(String[] args) { testValidationAndParser(); testRepository(); testImportRecovery(); testOrderingAndCompletion(); testReports(); System.out.println("All tracker checks passed"); } static void testValidationAndParser() { TaskParser parser = new TaskParser(); Task task = parser.parse(" A1 ; Read ; 1 ; TODO "); check("normalized id", task.id().equals("A1")); check("normalized title", task.title().equals("Read")); check("minimum minutes", task.minutes() == 1); check("maximum minutes", parser.parse("A;Read;240;DONE").minutes() == 240); for (String line : new String[] { "A;Read;0;TODO", "A;Read;241;TODO", "A;Read;nope;TODO", "A;Read;25;", "A;Read;25;todo", "A;;25;TODO", ";Read;25;TODO", "A;Read;25;TODO;extra" }) { try { parser.parse(line); throw new AssertionError("accepted invalid line: " + line); } catch (IllegalArgumentException expected) { // Only a documented input rejection counts as passing. } } } static void testRepository() { TaskRepository repository = new MemoryTaskRepository(); Task original = new Task("A1", "Read", 25, Status.TODO); repository.add(original); try { repository.add(new Task("A1", "Lost", 10, Status.DONE)); throw new AssertionError("duplicate accepted"); } catch (IllegalArgumentException expected) { check("duplicate kept original", repository.find("A1") == original); } List<Task> snapshot = repository.all(); snapshot.clear(); check("snapshot cannot clear store", repository.all().size() == 1); check("missing lookup", repository.find("missing") == null); try { repository.replace(new Task("missing", "Other", 10, Status.TODO)); throw new AssertionError("missing replacement accepted"); } catch (IllegalArgumentException expected) { check("missing replace leaves store", repository.all().size() == 1); } } static void testImportRecovery() { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); ImportResult result = service.importLines(new String[] { "A1;Read;25;TODO", "bad", " ", "A1;Lost;10;TODO", "B2;Test;10;TODO" }); check("accepted count", result.accepted() == 2); check("rejected count", result.errors().size() == 2); check("physical line number", result.errors().get(1).startsWith("Line 4:")); check("good line after rejection", repository.find("B2") != null); check("duplicate not overwritten", repository.find("A1").title().equals("Read")); result.errors().clear(); check("error snapshot isolated", result.errors().size() == 2); check("empty batch", service.importLines(new String[0]).accepted() == 0); } static void testOrderingAndCompletion() { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); service.importLines(new String[] { "B;Second;20;TODO", "A;First;20;TODO", "C;Long;30;TODO" }); check("tie broken by id", service.openOrdered().get(0).id().equals("A")); check("primary sort", service.openOrdered().get(2).id().equals("C")); check("sum open", service.openMinutes() == 70); Task before = repository.find("A"); check("complete existing", service.complete("A")); check("original immutable", before.status() == Status.TODO); check("new state", repository.find("A").status() == Status.DONE); check("completed excluded", service.openMinutes() == 50); check("complete repeated", service.complete("A")); check("repeat has same effect", service.openMinutes() == 50); check("missing completion", !service.complete("missing")); check("missing no new task", repository.all().size() == 3); } static void testReports() { List<Task> tasks = List.of( new Task("A", "Short", 10, Status.TODO), new Task("B", "Long", 30, Status.TODO), new Task("C", "Also long", 30, Status.TODO)); check("total of a List<Task>", Reports.totalMinutes(tasks) == 70); check("empty total", Reports.totalMinutes(List.of()) == 0); Task longest = Reports.longest(tasks); check("longest keeps Task type and first of a tie", longest.id().equals("B")); check("longest of empty", Reports.longest(List.<Task>of()) == null); } static void check(String name, boolean condition) { if (!condition) { throw new AssertionError(name); } } }
Hint 1: the idea

A test of "does not close" has to use the reader after importFrom returns. The existing tests can't see the difference, because they never touch the reader again. Turn the IOException a closed reader throws into a failing check, not a crash with an unrelated message.

Hint 2: a first step

You need three imports at the top of TrackerTest.java: BufferedReader, IOException and StringReader. Build the reader exactly as main in the Resources lesson did, around "A1;Read;25;TODO\n", and put both checks inside one try whose catch throws an AssertionError naming the broken promise.

Show one solution

Add these imports at the top of TrackerTest.java:

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

Call the new test from main, after testReports();:

Java
        testReaderStaysOpen();

Add the method next to the other tests:

Java
    static void testReaderStaysOpen() {
        TaskService service = new TaskService(new MemoryTaskRepository(), new TaskParser());
        BufferedReader reader = new BufferedReader(new StringReader("A1;Read;25;TODO\n"));
        try {
            check("imported", service.importFrom(reader).accepted() == 1);
            check("at end of input", reader.readLine() == null);
        } catch (IOException error) {
            throw new AssertionError("importFrom closed the caller's reader");
        }
    }

Expected output, and the output with the reader.close(); mutation:

Text
All tracker checks passed
Text
Exception in thread "main" java.lang.AssertionError: importFrom closed the caller's reader

The deciding line is reader.readLine() == null after importFrom: it is the only point where an open reader and a closed one behave differently (null versus IOException). The catch converts that IOException into an AssertionError with a message that names the contract, so the failing run says what broke rather than reporting a stream error. The mutation proves the check is not just decoration.

Change it and test again

Break one project rule at a time: remove duplicate rejection, remove the ID tie-breaker, include DONE tasks in reports, stop import after its first bad record, or count line numbers only for nonblank lines. For each defect, name the failing check. Restore the implementation before moving to another mutation. A passing test suite that survives these defects needs stronger cases.

Explain before moving on

Which tests protect behavior across classes? What does a rejection check prove about repository state after an error? Tests should describe the public contract, not depend on private map fields.

Was this article helpful?

Your response is saved on this device.