How to check String in response body with mockMvc

后端 未结 12 1900
遇见更好的自我
遇见更好的自我 2020-12-02 04:02

I have simple integration test

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName()          


        
12条回答
  •  日久生厌
    2020-12-02 04:53

    Here is an example how to parse JSON response and even how to send a request with a bean in JSON form:

      @Autowired
      protected MockMvc mvc;
    
      private static final ObjectMapper MAPPER = new ObjectMapper()
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .registerModule(new JavaTimeModule());
    
      public static String requestBody(Object request) {
        try {
          return MAPPER.writeValueAsString(request);
        } catch (JsonProcessingException e) {
          throw new RuntimeException(e);
        }
      }
    
      public static  T parseResponse(MvcResult result, Class responseClass) {
        try {
          String contentAsString = result.getResponse().getContentAsString();
          return MAPPER.readValue(contentAsString, responseClass);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    
      @Test
      public void testUpdate() {
        Book book = new Book();
        book.setTitle("1984");
        book.setAuthor("Orwell");
        MvcResult requestResult = mvc.perform(post("http://example.com/book/")
          .contentType(MediaType.APPLICATION_JSON)
          .content(requestBody(book)))
          .andExpect(status().isOk())
          .andReturn();
        UpdateBookResponse updateBookResponse = parseResponse(requestResult, UpdateBookResponse.class);
        assertEquals("1984", updateBookResponse.getTitle());
        assertEquals("Orwell", updateBookResponse.getAuthor());
      }
    

    As you can see here the Book is a request DTO and the UpdateBookResponse is a response object parsed from JSON. You may want to change the Jackson's ObjectMapper configuration.

提交回复
热议问题