Following tutorials show how to use MockMvc to test Controllers by
● performing HTTP Requests
● verifying HTTP Responses
Syntax
mockMvc.perform(get("/Hello")) //perform HTTP Request
.andExpect(status().isOk()); //verify HTTP Response
MockMvc can be instantiated in different ways as shown below.
@SpringBootTest, @Autowired
@SpringBootTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
@WebMvcTest, @Autowired
@WebMvcTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
MockMvcBuilders
class MyControllerTest {
MyController myController = new MyController();
@Test
void hello() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(myController).build();