Spring Boot 如何使用Spring的MockMvc和jsonpath测试不等式?

bxgwgixi  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(146)

我尝试测试响应中的字段是否等于某个值,如下所示:

  1. @Test
  2. void whenAnAuth0ExceptionIsThrown_itShouldNotLeakInformation() throws Exception {
  3. String description = "Resource not found.";
  4. Auth0Exception auth0Exception = new Auth0Exception(description);
  5. when(usersService.getRoles()).thenThrow(new UnrecoverableAuthException("api exception", auth0Exception));
  6. mockMvc.perform(get("/v1/users/roles").with(csrf()))
  7. .andExpect(status().isInternalServerError())
  8. .andExpect(jsonPath("$.errorMessage").value(AdditionalMatchers.not(description)));
  9. verify(usersService).getRoles();
  10. }

但当我尝试这样做时,我得到以下错误:

  1. org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
  2. No matchers found for additional matcher Not(?)

我发现的一个解决方法是使用andReturn(),然后测试MvcResult

sr4lhrrt

sr4lhrrt1#

你很接近了。

  1. import static org.hamcrest.Matchers.not;
  2. ...
  3. .andExpect(jsonPath("$.errorMessage").value(not(description)));

相关问题