Writing a unit test for the Hello World API returning a JSON

In the previous test, the REST API returned a string. However, in the real world, the REST API typically returns JSON responses.

Let's consider the http://localhost:8080/welcome-with-object API. The GET request to it would return a JSON, as shown in the following snippet of code:

{"message":"Hello World"}

How do we assert a JSON response?

In this test, let's take a shortcut, and test for a substring:

@Test
public void welcomeWithObject() throws Exception {
mvc.perform(
MockMvcRequestBuilders.get("/welcome-with-object")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}

This test is very similar to the earlier unit test, except that we are using containsString to check whether the content contains a "Hello World" substring. We will learn how to write proper JSON tests a little later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset