Capstone: a task tracker

The capstone puts the course together: a record for the model, a service with a map, ordinary tests, an exception test and a parameterised test. One expected value is wrong, so the first run is red; the fix is a number and the second run is green. Nothing in the page is new except the order of the parts.

The task model

Task.java is a record with an id, a title and a done flag. complete returns a new task with the flag set; a record is immutable, so the old value stays as it was.

public record Task(int id, String title, boolean done) { Task complete() { return new Task(id, title, true); } }

The service

TaskService.java keeps the tasks in a LinkedHashMap so the order is stable. add rejects a duplicate id, complete replaces the task with its completed copy and rejects a missing id, and open counts the tasks that are not done.

import java.util.LinkedHashMap; import java.util.Map; public class TaskService { private final Map<Integer, Task> tasks = new LinkedHashMap<>(); void add(int id, String title) { if (tasks.containsKey(id)) { throw new IllegalStateException("duplicate id: " + id); } tasks.put(id, new Task(id, title, false)); } Task complete(int id) { Task task = tasks.get(id); if (task == null) { throw new IllegalArgumentException("no task: " + id); } Task done = task.complete(); tasks.put(id, done); return done; } long open() { return tasks.values().stream().filter(task -> !task.done()).count(); } }

The test class

Five methods cover the service: add, complete, the open count, a missing id and a title kept through the round trip. The last one is parameterised, so it runs twice. The open-count test expects 2 while the service returns 1, which is the red case.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class TaskServiceTest { @Test void addsATask() { TaskService service = new TaskService(); service.add(1, "write"); assertEquals(1, service.complete(1).id()); } @Test void completesATask() { TaskService service = new TaskService(); service.add(1, "write"); assertTrue(service.complete(1).done()); } @Test void countsOpenTasks() { TaskService service = new TaskService(); service.add(1, "write"); service.add(2, "read"); service.complete(1); assertEquals(2, service.open()); } @Test void rejectsAMissingTask() { TaskService service = new TaskService(); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, () -> service.complete(9)); assertEquals("no task: 9", error.getMessage()); } @ParameterizedTest @ValueSource(strings = {"write", "read"}) void keepsTheTitle(String title) { TaskService service = new TaskService(); service.add(1, title); assertEquals(title, service.complete(1).title()); } }

The red run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Task.java TaskService.java TaskServiceTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ TaskServiceTest ✔
│     ├─ countsOpenTasks() ✘ expected: <2> but was: <1>
│     ├─ addsATask() ✔
│     ├─ keepsTheTitle(String) ✔
│     │  ├─ [1] write ✔
│     │  └─ [2] read ✔
│     ├─ rejectsAMissingTask() ✔
│     └─ completesATask() ✔
└─ JUnit Vintage ✔

Failures (1):
  JUnit Jupiter:TaskServiceTest:countsOpenTasks()
    MethodSource [className = 'TaskServiceTest', methodName = 'countsOpenTasks', methodParameterTypes = '']
    => org.opentest4j.AssertionFailedError: expected: <2> but was: <1>
       org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
       org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
       org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:197)
       org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:166)
       org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:161)
       org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:632)
       TaskServiceTest.countsOpenTasks(TaskServiceTest.java:30)
       java.base/java.lang.reflect.Method.invoke(Method.java:580)
       java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
       java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

Test run finished after 644 ms
[         5 containers found      ]
[         0 containers skipped    ]
[         5 containers started    ]
[         0 containers aborted    ]
[         5 containers successful ]
[         0 containers failed     ]
[         6 tests found           ]
[         0 tests skipped         ]
[         6 tests started         ]
[         0 tests aborted         ]
[         5 tests successful      ]
[         1 tests failed          ]

The fix

Two tasks were added, one was completed, so one is open. The service is right and the test expects one too many. Change assertEquals(2, service.open()) to assertEquals(1, service.open()). The fixed file is below.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class TaskServiceTest { @Test void addsATask() { TaskService service = new TaskService(); service.add(1, "write"); assertEquals(1, service.complete(1).id()); } @Test void completesATask() { TaskService service = new TaskService(); service.add(1, "write"); assertTrue(service.complete(1).done()); } @Test void countsOpenTasks() { TaskService service = new TaskService(); service.add(1, "write"); service.add(2, "read"); service.complete(1); assertEquals(1, service.open()); } @Test void rejectsAMissingTask() { TaskService service = new TaskService(); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, () -> service.complete(9)); assertEquals("no task: 9", error.getMessage()); } @ParameterizedTest @ValueSource(strings = {"write", "read"}) void keepsTheTitle(String title) { TaskService service = new TaskService(); service.add(1, title); assertEquals(title, service.complete(1).title()); } }

The green run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Task.java TaskService.java TaskServiceTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ TaskServiceTest ✔
│     ├─ countsOpenTasks() ✔
│     ├─ addsATask() ✔
│     ├─ keepsTheTitle(String) ✔
│     │  ├─ [1] write ✔
│     │  └─ [2] read ✔
│     ├─ rejectsAMissingTask() ✔
│     └─ completesATask() ✔
└─ JUnit Vintage ✔

Test run finished after 630 ms
[         5 containers found      ]
[         0 containers skipped    ]
[         5 containers started    ]
[         0 containers aborted    ]
[         5 containers successful ]
[         0 containers failed     ]
[         6 tests found           ]
[         0 tests skipped         ]
[         6 tests started         ]
[         0 tests aborted         ]
[         6 tests successful      ]
[         0 tests failed          ]

The course in one suite

The capstone uses the value test, the exception test, the record, the parameterised source and the red-green loop, which are the spine of the course. A real project adds the tags, the reports folder and the layout from the previous part; the tests themselves look like these. The course index lists every lesson, and the articles on testing Java code go deeper on the launcher and the framework.

Exercises

  1. Fix the count and run. Copy the two counts lines that change.
  2. Add a test for a duplicate id and assert the message.
  3. Add a done list method and a parameterised test over two ids.
  4. Add a @Tag("capstone") and run only that tag.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Task.complete return?

    Answer

    A new Task with done set to true

    A record is immutable, so complete builds a new value with the flag set.

  2. How many tasks are open after adding two and completing one?

    Answer

    One

    One of the two is done, so one remains open.

  3. What does the parameterised title test cover?

    Answer

    That the title survives add and complete for two values

    The same round trip runs once per string in the source.

  4. What does this program print? public class Q1 { public static void main(String[] args) { record Task(int id, boolean done) { } Task task = new Task(1, false); System.out.println(task.done()); } }

    Answer

    false

    The accessor returns the done component, which is false.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(2 + 1); } }

    Answer

    3

    The two integers are added, and println prints 3.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println("no task: 9".contains("9")); } }

    Answer

    true

    The message contains the digit, so contains is true.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println("write".length()); } }

    Answer

    5

    The word write has five letters.

  8. Why is the duplicate id an error rather than an overwrite?

    Answer

    The service chooses a rule the map would not enforce by itself

    A Map.put replaces silently, so the service adds the rule it wants and a test pins it.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println("read".toUpperCase()); } }

    Answer

    READ

    toUpperCase changes every letter to upper case.

  10. What ends the red-green loop of the capstone?

    Answer

    One expected value changes from 2 to 1, and the suite is green

    The service was right and the test expected one task too many; one number fixes it.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev