JsonPathResultMatchers不能应用于ResultMatcher

use*_*277 4 java spring-boot spring-boot-test

我正在尝试使用Spring Boot做一个简单的测试。

mockMvc.perform(post("/user")
       .contentType(MediaType.APPLICATION_JSON)
       .content(objectMapper.writeValueAsString(userJohn)))
       .andExpect(jsonPath("$[0].username", is("bob")));
Run Code Online (Sandbox Code Playgroud)

将此导入用于jsonPath:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
Run Code Online (Sandbox Code Playgroud)

我得到:

andExpect (org.springframework.test.web.servlet.ResultMatcher) in ResultActions cannot be applied to (org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath)
Run Code Online (Sandbox Code Playgroud)

如果我尝试将其强制转换为(ResultMatcher),则会得到:

java.lang.ClassCastException: org.springframework.test.web.servlet.result.JsonPathResultMatchers cannot be cast to org.springframework.test.web.servlet.ResultMatcher
Run Code Online (Sandbox Code Playgroud)

我正在使用Spring Boot的2.0.4版本。有什么问题的想法吗?

谢谢

小智 12

试试吧:

mockMvc.perform(post("/user")
   .contentType(MediaType.APPLICATION_JSON)
   .content(objectMapper.writeValueAsString(userJohn)))
   .andExpect(jsonPath("$[0].username").value("bob"));
Run Code Online (Sandbox Code Playgroud)

我不知道这些变化什么时候。看更多 :

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/JsonPathResultMatchers.html