对controller进行单元测试的几个坑 - HavenTong/MeetHere-backend GitHub Wiki

GET请求

对于GET请求,后端通过@RequestParam进行接收的参数,通过param()方法在模拟的请求中填入参数:

Example:

    @Test
    @DisplayName("发送验证码时,发送正确的邮箱")
    void shouldSendCorrectEmailWhenSendCheckCode() throws Exception{
        ResultActions perform = mockMvc.perform(get("/customer/check-code").
                param("email", "[email protected]"));
        perform.andExpect(status().isOk());
        perform.andExpect(jsonPath("$.message").value("success"));
        verify(customerService, times(1))
                        .sendCheckCode("[email protected]");

    }

POST请求

POST请求参数为JSON,后端通过@RequestBody进行接收。这种参数需要在模拟请求中通过contentType()方法指定请求参数的类型,同时参数内容需要通过content()方法指定,content()的参数是一个JSON字符串。可以通过JSON.toJSONString()方法(位于新添加的fastjson依赖中)将Java对象转成JSON字符串:

Example:

    @Test
    @DisplayName("注册时,注册正确的用户")
    void shouldRegisterCorrectUser() throws Exception{
        CustomerRequest customerRequest = CustomerRequest.builder()
                .email("[email protected]").userName("root")
                .password("123456").checkCode("123456").build();
      
        ResultActions perform = mockMvc.perform(post("/customer/register")
        .contentType(MediaType.APPLICATION_JSON)
        .content(JSON.toJSONString(customerRequest)));
      
        perform.andExpect(status().isOk())
                .andExpect(jsonPath("$.message").value("success"));
        verify(customerService, times(1))
                .register(customerRequest);
    }

jsonPath

在上方的代码中,perform需要使用jsonPath()方法,通过jsonPath表达式才能拿到controller返回的JSON格式数据,我们项目中的ResultEntity返回时转成的JSON格式为:

{
  "data": "",
  "code": "",
  "message": "" 
}

表达式"$.message"则取出的是其中message属性的值

具体的更多jsonPath的Example可以见:https://goessner.net/articles/JsonPath/