liveBook · Manning

JSON

As explained in Testing Spring Boot Applications

JSON is a text-based data interchange format representing structured values and objects.

JSON carries data between a Spring Boot HTTP API and a browser interface. An initial page can arrive as rendered HTML; later JavaScript requests read JSON responses and update the page. section 4.1

For an API test, MockMvcTester can request an endpoint and AssertJ can inspect its JSON body. A lenient comparison checks expected fields, while a path assertion checks a particular value, such as a generated city ID. section 4.1

Alternatively, convert the response to Java objects for field-level assertions. For a POST request, set the content type to application/json and supply a JSON request body. section 4.1

Listing 4.3 MockMvcTester API tests
@Test
void getWeather() {
  var paris = selectCity("Paris");

  var response = mvc.get().uri("/api/weather").exchange();

  assertThat(response)
    .hasStatus(HttpStatus.OK)
    .bodyJson() #1
    .isLenientlyEqualTo( #2
          """
          [
            {
              "cityName": "Paris",
              "country": "France",
              "weather": "Clear sky",
              "temperature": 20.0,
              "windSpeed": 0.0
            }
          ]
          """)
    .extractingPath("$.[0].cityId") #3
      .isEqualTo(paris.getId());
}

The weather API test combines a lenient JSON comparison with a path assertion for the city ID. section 4.1

How Testing Spring Boot Applications covers it

How deep it goes
Works through JSON request and response assertions, including object conversion, without explaining the format’s specification.
Examples
Uses a weather API response, a city ID path assertion, a Java record conversion, and a JSON POST body.
What it assumes
Assumes a Spring Boot web application and prior familiarity with test mocks and helper functions.
What you can do after
Apply it via MockMvcTester to send JSON requests and assert JSON responses.
How it connects
Connects JSON to HTTP APIs, JavaScript, MockMvcTester, AssertJ, and Java records.

Also explained in

Compare how 42 books explain JSON →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.