Let's quickly write a unit test for the preceding method. We will want to pass a name as a part of the URI and check whether the response contains the name. The following code shows how we can do that:
@Test
fun `GET welcome-with-parameter returns "Hello World, Buddy"`() {
mvc.perform(
MockMvcRequestBuilders.get(
"/welcome-with-parameter/name/Buddy")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(
containsString("Hello World, Buddy")));
}
A few important things to note are as follows:
- MockMvcRequestBuilders.get("/welcome-with-parameter/name/Buddy"): This matches against the variable template in the URI. We will pass in the name, .
- .andExpect(content().string(containsString("Hello World, Buddy"))): We expect the response to contain the message with the name.