Tests through the launcher

The service is designed so that most of it can be tested without a socket: the routing is a function, the model is a record and the JSON is a method. Eight of the nine tests call those directly, and the ninth starts a server on port 0 and makes one real request, which is the only way to know that the handler and the bytes are wired correctly.

The class under test

The service file is the one from the server page with no change: this is the version the project ships. The test class is in the same package, so it reaches the package-private methods and the nested records without an import:

package library; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; public class Desk { record Loan(int id, String member, String title, LocalDate due, LocalDate returned) { State state(LocalDate today) { if (returned != null) { return new Returned(returned); } long days = ChronoUnit.DAYS.between(due, today); if (days > 0) { return new Overdue(days); } if (days >= -2) { return new DueSoon(-days); } return new OnLoan(-days); } String toJson(LocalDate today) { return "{" + field("id", id) + "," + field("member", member) + "," + field("title", title) + "," + field("due", due.toString()) + "," + Q + "state" + Q + ":" + stateJson(state(today)) + "}"; } } sealed interface State permits OnLoan, DueSoon, Overdue, Returned { } record OnLoan(long daysLeft) implements State { } record DueSoon(long daysLeft) implements State { } record Overdue(long daysLate) implements State { } record Returned(LocalDate on) implements State { } static final LocalDate TODAY = LocalDate.of(2026, 11, 20); static final List<Loan> LOANS = List.of( new Loan(1, "Ada", "Dune", LocalDate.of(2026, 11, 25), null), new Loan(2, "Grace", "The Dispossessed", LocalDate.of(2026, 11, 21), null), new Loan(3, "Alan", "Snow Crash", LocalDate.of(2026, 11, 14), null), new Loan(4, "Edsger", "Programming Pearls", LocalDate.of(2026, 11, 10), LocalDate.of(2026, 11, 18))); static final String Q = String.valueOf((char) 34); static final String B = String.valueOf((char) 92); static String field(String name, String value) { return Q + name + Q + ":" + quote(value); } static String field(String name, int value) { return Q + name + Q + ":" + value; } static String quote(String text) { StringBuilder out = new StringBuilder(Q); for (char c : text.toCharArray()) { if (c == 34) { out.append(B).append(Q); } else if (c == 92) { out.append(B).append(B); } else { out.append(c); } } return out.append(Q).toString(); } static String stateJson(State state) { return switch (state) { case OnLoan onLoan -> "{" + field("kind", "on_loan") + "," + field("days", (int) onLoan.daysLeft()) + "}"; case DueSoon dueSoon -> "{" + field("kind", "due_soon") + "," + field("days", (int) dueSoon.daysLeft()) + "}"; case Overdue overdue -> "{" + field("kind", "overdue") + "," + field("days", (int) overdue.daysLate()) + "}"; case Returned returned -> "{" + field("kind", "returned") + "," + field("on", returned.on().toString()) + "}"; }; } static String array(List<Loan> loans, LocalDate today) { StringBuilder out = new StringBuilder("["); for (int i = 0; i < loans.size(); i++) { if (i > 0) { out.append(','); } out.append(loans.get(i).toJson(today)); } return out.append(']').toString(); } record Reply(int status, String body) { } static List<Loan> overdue() { List<Loan> result = new ArrayList<>(); for (Loan loan : LOANS) { if (loan.state(TODAY) instanceof Overdue) { result.add(loan); } } return result; } static Reply route(String path) { if ("/health".equals(path)) { return new Reply(200, "{" + field("status", "ok") + "," + field("loans", LOANS.size()) + "}"); } if ("/loans".equals(path)) { return new Reply(200, array(LOANS, TODAY)); } if ("/loans/overdue".equals(path)) { return new Reply(200, array(overdue(), TODAY)); } if (path.startsWith("/loans/")) { try { int id = Integer.parseInt(path.substring("/loans/".length())); for (Loan loan : LOANS) { if (loan.id() == id) { return new Reply(200, loan.toJson(TODAY)); } } } catch (NumberFormatException e) { return new Reply(400, "{" + field("error", "bad id") + "}"); } return new Reply(404, "{" + field("error", "no such loan") + "}"); } return new Reply(404, "{" + field("error", "no route") + "}"); } static HttpServer start(int port) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", Desk::handle); server.start(); return server; } static void handle(HttpExchange exchange) throws IOException { Reply reply = route(exchange.getRequestURI().getPath()); send(exchange, reply.status(), reply.body()); } static void send(HttpExchange exchange, int status, String body) throws IOException { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8"); exchange.sendResponseHeaders(status, bytes.length); try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); } } public static void main(String[] args) throws Exception { if (args.length > 0 && "serve".equals(args[0])) { HttpServer server = start(8091); System.out.println("listening on " + server.getAddress().getPort()); new java.util.concurrent.CountDownLatch(1).await(); return; } HttpServer server = start(8091); System.out.println("listening on " + server.getAddress().getPort()); try (HttpClient client = HttpClient.newHttpClient()) { for (String path : List.of("/health", "/loans/2", "/loans/overdue", "/loans/9")) { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path)) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("GET " + path + " -> " + response.statusCode() + " " + response.body()); } } server.stop(0); System.out.println("stopped"); } }

The test class

Nine tests in three groups. Four check a state through the route, so the model and its JSON are checked together. Three check the escapes and the two failure statuses. Two check the socket and the overdue filter. The order annotation keeps the report in the same order on every run:

package library; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.sun.net.httpserver.HttpServer; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(MethodOrderer.MethodName.class) public class DeskTest { @Test void jsonEscapesAQuote() { String text = "a" + (char) 34 + "b"; assertEquals(Desk.Q + "a" + Desk.B + Desk.Q + "b" + Desk.Q, Desk.quote(text)); } @Test void overdueListHoldsOnlyTheLateLoan() { String body = Desk.route("/loans/overdue").body(); assertTrue(body.contains("Snow Crash")); assertFalse(body.contains("Dune")); } @Test void routeAnswers404ForAMissingLoan() { assertEquals(404, Desk.route("/loans/9").status()); assertTrue(Desk.route("/loans/9").body().contains("no such loan")); } @Test void routeReturnsTheLoan() { assertEquals(200, Desk.route("/loans/2").status()); assertTrue(Desk.route("/loans/2").body().contains("Grace")); } @Test void serverAnswersOverHttp() throws Exception { HttpServer server = Desk.start(0); try { try (HttpClient client = HttpClient.newHttpClient()) { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/health")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(200, response.statusCode()); assertTrue(response.body().contains("loans")); } } finally { server.stop(0); } } @Test void stateOfADueSoonLoan() { assertTrue(Desk.route("/loans/2").body().contains("\"kind\":\"due_soon\",\"days\":1")); } @Test void stateOfAFreshLoan() { assertTrue(Desk.route("/loans/1").body().contains("\"kind\":\"on_loan\",\"days\":5")); } @Test void stateOfAnOverdueLoan() { assertTrue(Desk.route("/loans/3").body().contains("\"kind\":\"overdue\",\"days\":6")); } @Test void stateOfAReturnedLoan() { assertTrue(Desk.route("/loans/4").body().contains("\"kind\":\"returned\",\"on\":\"2026-11-18\"")); } }

The model and the JSON

The state tests assert on the JSON fragment "kind":"on_loan","days":5 rather than on a string built by hand. That checks three things at once: the date rule chose the right record, the switch wrote the right name and the number is the one the arithmetic gives. The escape test builds its quote character as (char) 34 for the same reason the writer does, and compares the escaped form with the constants of the class.

The one socket test

serverAnswersOverHttp starts the service on port 0, which asks the operating system for a free port, reads the port back from the server and calls /health. The finally stops the server: a test that leaves one running keeps the JVM alive, and the next run would find the port taken. The port 0 is what lets two runs of the suite go at the same time.

The run

The compile needs the launcher jar on its class path because the test class imports the framework, and the run selects the class by its package name:

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out src/library/Desk.java src/library/DeskTest.java
junit execute --class-path out --select-class library.DeskTest --disable-ansi-colors

The report

Nine leaves, nine green marks, and the counts at the bottom. The time is the machine's and changes between runs; the counts do not:


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

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ DeskTest ✔
│ ├─ jsonEscapesAQuote() ✔
│ ├─ overdueListHoldsOnlyTheLateLoan() ✔
│ ├─ routeAnswers404ForAMissingLoan() ✔
│ ├─ routeReturnsTheLoan() ✔
│ ├─ serverAnswersOverHttp() ✔
│ ├─ stateOfADueSoonLoan() ✔
│ ├─ stateOfAFreshLoan() ✔
│ ├─ stateOfAReturnedLoan() ✔
│ └─ stateOfAnOverdueLoan() ✔
└─ JUnit Vintage ✔

Test run finished after 871 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 9 tests found ]
[ 0 tests skipped ]
[ 9 tests started ]
[ 0 tests aborted ]
[ 9 tests successful ]
[ 0 tests failed ]

The next page

The next page packs the compiled classes into a runnable jar and runs the three checkers over the same source: checkstyle with the rules of the project, PMD with its quickstart set and SpotBugs over the class files. The Java course covers the framework in lesson 127, and the testing group has the long form of every annotation used here.

The code on this page was compiled with OpenJDK 21.0.13 (javac) and run with the JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container. The time in the report is that machine's and changes between runs.

Article author: Arthur Isaev