Подтвердить что ты не робот

mockMvc - тестовое сообщение об ошибке

У кого-нибудь есть какие-либо советы, или кто-нибудь знает, как я могу проверить "сообщение об ошибке", возвращаемое объектом ответа HTTP?

@Autowired
private WebApplicationContext ctx;

private MockMvc mockMvc;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}

Отклик:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[application/json;charset=UTF-8]}
        Content type = application/json;charset=UTF-8
4b9b3361

Ответ 1

Вы можете использовать метод status.reason().

Например:

     @Test
     public void loginWithBadCredentials() {
        this.mockMvc.perform(
                post("/rest/login")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"username\": \"baduser\", \"password\": \"invalidPassword\"}")
                )
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isUnauthorized())
                .andExpect(status().reason(containsString("Bad credentials")))
                .andExpect(unauthenticated());
    }


    MockHttpServletResponse:
                  Status = 401
           Error message = Authentication Failed: Bad credentials
            Content type = null
                    Body = 
           Forwarded URL = null
          Redirected URL = null
                 Cookies = []

Ответ 2

Еще проще:

String error =  mockMvc...
    .andExpect(status().isUnauthorized())
    .andReturn().getResolvedException().getMessage();

assertTrue(StringUtils.contains(error, "Bad credentials"));

Ответ 3

Это решение, которое я нашел с помощью JsonPath и MockMvc

this.mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(responseJson)).andDo(print())
.andExpect(status().is5xxServerError())
.andExpect(jsonPath("$.message", is("There is an error while executing this test request ")));

Надеюсь, это поможет.