Capstone 3: tests and a runnable jar

The last lesson of the course is the service of lesson 134 with its tests and its packaging: two files, the service and a test class, a launcher run of five tests, a jar with a Main-Class and java -jar that starts it. It is the same project as the two lessons before, seen the way a build tool would see it.

The project as two files

The service moves its routing out of the handler into two static methods, route and status, so a test can call them without a socket. The handler becomes three lines, and start takes the port, which is what lets a test use port 0 and get a free one.

The project is two source files and two commands: one compile with the launcher jar on the class path, one launcher run that scans the folder. A build tool would run the same two commands with the jar named in a pom, which is the lesson before this one.

Service.java

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.nio.charset.StandardCharsets; import java.util.List; public class Service { record Task(int id, String title, boolean done) { String toJson() { return "{\"id\":" + id + ",\"title\":\"" + title + "\",\"done\":" + done + "}"; } } static final List<Task> TASKS = List.of( new Task(1, "write the report", false), new Task(2, "read the spec", true), new Task(3, "answer mail", false)); static String route(String path) { if (path.equals("/health")) { return "{\"status\":\"ok\",\"tasks\":" + TASKS.size() + "}"; } if (path.equals("/tasks")) { StringBuilder out = new StringBuilder("["); for (int i = 0; i < TASKS.size(); i++) { if (i > 0) { out.append(','); } out.append(TASKS.get(i).toJson()); } return out.append(']').toString(); } String last = path.substring(path.lastIndexOf('/') + 1); for (Task task : TASKS) { if (String.valueOf(task.id()).equals(last)) { return task.toJson(); } } return "{\"error\":\"no such task\"}"; } static int status(String path) { return route(path).startsWith("{\"error\"") ? 404 : 200; } static HttpServer start(int port) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", Service::handle); server.start(); return server; } static void handle(HttpExchange exchange) throws IOException { String path = exchange.getRequestURI().getPath(); send(exchange, status(path), route(path)); } 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 IOException { HttpServer server = start(8080); System.out.println("listening on " + server.getAddress().getPort()); System.out.println("health: " + route("/health")); System.out.println("task 2: " + route("/tasks/2")); System.out.println("missing: " + status("/tasks/9") + " " + route("/tasks/9")); server.stop(0); System.out.println("stopped"); } }

ServiceTest.java

Four tests call the routing directly and one starts a server on port 0 and makes a real request through HttpClient. The port 0 is the trick: the operating system picks a free one, the test reads it back from the server, and two runs of the test can go at the same time.

import static org.junit.jupiter.api.Assertions.assertEquals; 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 ServiceTest { @Test void healthCountsTheTasks() { assertEquals("{\"status\":\"ok\",\"tasks\":3}", Service.route("/health")); } @Test void tasksIsAnArrayOfThree() { String body = Service.route("/tasks"); assertTrue(body.startsWith("[")); assertEquals(3, body.split("\\{\"id\"").length - 1); } @Test void oneTaskById() { assertEquals("{\"id\":2,\"title\":\"read the spec\",\"done\":true}", Service.route("/tasks/2")); } @Test void unknownTaskIs404() { assertEquals(404, Service.status("/tasks/9")); assertTrue(Service.route("/tasks/9").contains("no such task")); } @Test void serverAnswersOverHttp() throws Exception { HttpServer server = Service.start(0); try { int port = server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:" + port + "/health")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(200, response.statusCode()); assertTrue(response.body().contains("\"status\":\"ok\"")); } finally { server.stop(0); } } }

The fourth test splits on \{\"id\" and counts the parts, which is a cheap way to count the objects of the array without a parser. The fifth has a finally that stops the server, because a test that leaves a server running keeps the JVM alive and the next test on that port fails.

The test run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Service.java ServiceTest.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 ✔
│ └─ ServiceTest ✔
│ ├─ healthCountsTheTasks() ✔
│ ├─ oneTaskById() ✔
│ ├─ serverAnswersOverHttp() ✔
│ ├─ tasksIsAnArrayOfThree() ✔
│ └─ unknownTaskIs404() ✔
└─ JUnit Vintage ✔

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

Five tests, five green marks, and the run takes a second and a half because the last one starts a server and makes a request. The time is the machine's and changes; the counts do not. A failure would print the assertion message and the two values, as lesson 127 showed.

The runnable jar

The service is compiled on its own into classes, and the jar takes that folder with a Main-Class. The test class is not in the jar, which is the rule a build tool follows: tests ship with the build and not with the program.

javac -Xlint:all -d classes Service.java
jar --create --file service.jar --main-class Service -C classes .
jar --list --file service.jar

META-INF/
META-INF/MANIFEST.MF
Service$Task.class
Service.class

The nested record appears as Service$Task.class, the dollar of lesson 100, and the jar of 3889 bytes holds the two class files and the manifest. The run is the one of lesson 134, with no class path and no folder:

java -jar service.jar

listening on 8080
health: {"status":"ok","tasks":3}
task 2: {"id":2,"title":"read the spec","done":true}
missing: 404 {"error":"no such task"}
stopped

The status of that run is 0, because the program stopped its server and returned. A service that is deployed does not stop: it starts the server and waits, which is the serve mode of lesson 134 and the shape of the ENTRYPOINT of a container.

The end of the course

The three capstones are the course in miniature. The JSON value is types: a sealed hierarchy, records and an exhaustive switch. The task list is classes and files: a model that validates, a store that owns its state, a format that survives a round trip, and a command line with statuses. The service is the platform: the JDK's own HTTP server and client, a build with a jar, and the tests that prove the routes and the socket.

The three article groups after the lessons go deeper: JUnit 5 in full, Java against C++, and a modern project built with the JDK only. The course index lists every lesson, and each one builds and runs in the container that wrote it.

Exercises

  1. Add a test that the content type of the HTTP response is application/json.
  2. Make the jar print its own version from the manifest and run it.
  3. Add a sixth route and a test for it, and run the launcher again.
  4. Build the jar with the test class inside and explain why that is a bad idea.

Questions

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

  1. Why does the test start the server on port 0?

    Answer

    The operating system picks a free port, so two runs do not collide

    The test reads the port back from the server, which is what makes it independent of the machine.

  2. Why is the test class not in the jar?

    Answer

    Tests ship with the build and not with the program

    The jar is the deliverable, and a test is part of the build that proves it.

  3. What does the fifth test do that the first four do not?

    Answer

    It starts a server and makes a real HTTP request

    The four call the routing directly, and the fifth proves the socket and the handler.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String body = "[{\"id\":1},{\"id\":2}]"; int count = 0; for (String part : body.split(",")) { if (part.contains("id")) { count++; } } System.out.println(count); } }

    Answer

    2

    The body holds two objects, and the split gives one more part than the separators.

  5. Why does the handler become three lines in this version?

    Answer

    The routing is in static methods, so a test can call them without a socket

    Moving the decision out of the handler is what makes four of the five tests plain calls.

  6. Why does the test of the socket stop the server in a finally?

    Answer

    A server left running keeps the JVM alive and the port taken

    The finally runs on every path, which is the lesson of the try-with-resources applied to a server.

  7. What does the manifest of the jar carry that makes it runnable?

    Answer

    The Main-Class line

    java -jar reads the line and starts that class, which is lesson 126.

  8. What does this program print? public class Q2 { record Task(int id, String title) { String toJson() { return "{\"id\":" + id + ",\"title\":\"" + title + "\"}"; } } public static void main(String[] args) { System.out.println(new Task(1, "a").toJson()); } }

    Answer

    {"id":1,"title":"a"}

    The method joins the quotes and the values into the JSON form of the record.

  9. Which build step puts the classes into the jar?

    Answer

    jar --create with -C classes .

    javac makes the class files and jar packs them with the manifest.

  10. What happens when a test leaves its server running?

    Answer

    The JVM does not exit and the next run finds the port taken

    A live server thread keeps the process alive, which is why the finally is there.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev