如何测试jSON对象是否与我使用Mockito发布它相同?

时间:2017-07-20 09:14:02

标签: java spring rest post mockito

这是我的终点:

 @PostMapping("/email/registration")
  public Data registration(@RequestBody Data data, HttpServletRequest 
  httpServletRequest) throws Exception {
  emailSenderService.pushEmail(httpServletRequest.getRequestURI(),          
  emailSenderService.sendConfirmationEmail(httpServletRequest.getRequestURI(), data));
  emailSenderService.consumeEmail(httpServletRequest.getRequestURI());
  return data;
  }

这是我的测试(当然它不起作用):

  @Test
  public void testRegistrationConfirmation() throws Exception {
      Data testData = new Data();
      when(testData).thenReturn(testData);
      mockMvc.perform(
              post("/email/registration")
                      .contentType(MediaType.APPLICATION_JSON)
                      .content(asJsonString(testData)))
              .andExpect(status().isOk())
              .andExpect(testData);
  }

我想看看给定对象是否与返回对象相同,最好不要用值填充所有字段。 谢谢你的答案!

1 个答案:

答案 0 :(得分:0)

它可能更优雅,但你可以使用杰克逊为你制作json:

@Test
  public void testRegistrationConfirmation() throws Exception {
      Data testData = new Data();
      when(testData).thenReturn(testData);
      mockMvc.perform(
              post("/email/registration")
                      .contentType(MediaType.APPLICATION_JSON)
                      .content(asJsonString(testData)))
              .andExpect(status().isOk())
              .andExpect(content().string(equalTo(new ObjectMapper().writeValueAsString(testData))));
  }