Chapter 1: New Language Features Explain Unexpected Empty Optional →

Inline Short Files in Tests

class SupplyTests {

  @Test
  void updateBarcode() throws JSONException {
    var supply = new Supply("1234", 5);

    var actualJson = supply.toJson();

    var expectedJson = read("/supply.json");
    assertEquals(expectedJson, actualJson, STRICT);
  }

}

This JUnit 5 test checks the JSON representation of a Supply with JSONAssert. The expected JSON lives in a separate file under src/test/resources, which a helper reads from the classpath.

That's a common pattern, but it makes the test harder to read. The most important part, the expected output, is not visible in the test itself, it's one click away. When the test fails, you have to jump between two files to understand why. And over time, the resource folder fills up with files whose tests nobody remembers.

class SupplyTests {

    @Test
    void updateBarcode() throws JSONException {
        var supply = new Supply("1234", 5);

        var actualJson = supply.toJson();

        var expectedJson = """
                {
                  "id": "1234",
                  "count": 5
                }""";
        assertEquals(expectedJson, actualJson, STRICT);
    }
}

Since Java 15, text blocks let you write multi-line strings without escaping quotes or concatenating lines. So the expected JSON fits right into the test, formatted just like in the file before. Everything you need to understand the test is now in one place.

The helper method and the resource file are gone. If you need to vary parts of the expected output, combine the text block with formatted(). Keep separate files for large inputs, though: inlining pays off for short snippets that you'd want to see at a glance.