Let's quickly write a unit test for the preceding method. We would want to pass a name as part of the URI and check whether the response contains the name. The following code shows how we can do that:
@Test
public void welcomeWithParameter() throws Exception {
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 pass in the name Buddy.
- .andExpect(content().string(containsString("Hello World, Buddy”))): We expect the response to contain the message with the name.