Let's quickly write a unit test to test the preceding controller method:
@RunWith(SpringRunner.class)
@WebMvcTest(BasicController.class)
public class BasicControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void welcome() throws Exception {
mvc.perform(
MockMvcRequestBuilders.get("/welcome")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(
equalTo("Hello World")));
}
}
In the preceding unit test, we will launch up a Mock MVC instance with BasicController. A few quick things to note are as follows:
- @RunWith(SpringRunner.class): SpringRunner is a shortcut to the SpringJUnit4ClassRunner annotation. This launches up a simple Spring context for unit testing.
- @WebMvcTest(BasicController.class): This annotation can be used along with SpringRunner to write simple tests for Spring MVC controllers. This will load only the beans annotated with Spring-MVC-related annotations. In this example, we are launching a Web MVC Test context with the class under test being BasicController.
- @Autowired private MockMvc mvc: Autowires the MockMvc bean that can be used to make requests.
- 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".