mockito 使用MockMvc post方法测试Spring控制器

6rvt4ljy  于 2022-11-08  发布在  Spring
关注(0)|答案(4)|浏览(190)

我尝试在Spring Boot应用程序中测试我的控制器的一个方法。这是一个post端点,它在一个请求中获取一个id,并将此id传递给一个服务:

@Slf4j
@Controller
public class AdministrationController {

    private final AdministrationService administrationService;

    @Autowired
    public AdministrationController(AdministrationService administrationService) {
        this.administrationService = administrationService;
    }

    @PostMapping("/administration")
    public @ResponseBody ResponseEntity<String> deleteByMessageId(String id) {
        return new ResponseEntity<>(administrationService.deleteMessageById(id), HttpStatus.OK);
    }
}

该方法对控制器的测试:

RunWith(SpringRunner.class)
@WebMvcTest(AdministrationController.class)
public class AdministrationControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private AdministrationService service;

    @Test
    public void 
    deleteByMessageId_whenCalled_thenServiceMethodIsCalledWithRequestParameters() throws Exception {

        Object randomObj = new Object() {
            public final String id = "1234";
        };

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(randomObj);

        MvcResult result = mvc.perform(
            post("/administration")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(json))
            .andExpect(status().isOk())
            .andReturn();

        verify(service, times(1)).deleteMessageById("1234");
}

}
当我运行这个测试时,post请求被执行,但是主体是空的:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /administration
   Parameters = {}
      Headers = {Content-Type=[application/json]}
         Body = <no character encoding set>
Session Attrs = {}

看起来,即使我在测试中设置了内容,它也没有出现在我发送的请求中。而且,确实,测试失败了:

Argument(s) are different! Wanted: "1234"
Actual invocation has different arguments: null

我在这里遗漏了什么?我如何用MockMvc设置请求主体?

9njqaruj

9njqaruj1#

尝试使用.characterEncoding("utf-8"))

MvcResult result = mvc.perform(post("/administration")
    .contentType(MediaType.APPLICATION_JSON)
    .content(json)
    .characterEncoding("utf-8"))
    .andExpect(status().isOk())
    .andReturn();
j8ag8udp

j8ag8udp2#

另一个选项(受@stelios-anastasakis答案的启发)是在Content-Type报头中提供字符编码:

MvcResult result = mvc.perform(post("/administration")
    .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
    .content(json)
    .andExpect(status().isOk())
    .andReturn();

请注意,这里我们使用MediaType.APPLICATION_JSON_UTF8_VALUE而不是MediaType.APPLICATION_JSON

qlfbtfca

qlfbtfca3#

mockMvc.perform(post( "/request")
                .content(objectMapper.writeValueAsString(requestBody))
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andDo(print())
                .andExpect(status().isOk());
but5z9lq

but5z9lq4#

您肯定遗漏了方法参数的注解。

public @ResponseBody ResponseEntity<String> deleteByMessageId(String id)

应该是这样的:

public @ResponseBody ResponseEntity<String> deleteByMessageId(@RequestParam("id") String id)

如果要将其用作请求参数。
请看这里的Spring MVC文档。当然,编写测试取决于您对这里的id的期望。

相关问题