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

We would like to write a unit test for the hello world API, http://localhost:8080/welcome, which returns "Hello World".

In the unit test, we want to send a GET request to the resource at /welcome, and check whether the response is as expected.

The following code shows a unit test:

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

Here are a few key things to note:

  • mvc.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON)): Performs a request to /welcome, with the Accept header value, application/json
  • andExpect(status().isOk()): Expects that the status of the response is 200 (success)
  • andExpect(content().string(equalTo("Hello World"))): Expects that the content of the response is equal to "Hello World"
..................Content has been hidden....................

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