https://www.jianshu.com/p/4a8326d89991

@WebMvcTest

@WebMvcTest(controllers = UserController.class)
  • 这个注解仅用于Controller层的单元测试。默认情况下会仅实例化所有的Controller,可以通过指定单个Controller的方式实现对单个Controller的测试。

  • 同时,如果被测试的Controller依赖Service的话,需要对该Service进行mock,如使用@MockBean

  • 该注解的定义中还包括了@AutoConfigureMockMvc注解,因此,可以直接使用MockMvc对被测controller发起http请求。

示例代码

@WebMvcTest(controllers = UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    void register() throws Exception {
        UserVO userVO = new UserVO();
        userVO.setAccount("MyAccount");
        userVO.setNickName("MyName");
        userVO.setAge(10);
        userVO.setPassword("my_password");
        userVO.setSex(1);
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders
                .post(UserController.URL_REGISTER)
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(userVO));
        ResultActions perform = mockMvc.perform(request);
        perform.andReturn().getResponse().setCharacterEncoding("UTF-8");
        perform.andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print());
    }

}