JsonPath config for MockMvc



JsonPath本身可以这样配置

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
// ...
Configuration configuration = Configuration
.builder()
.options(Option.REQUIRE_PROPERTIES)
.build();
JsonPath
.using(configuration)
.parse(someJson)
.read("$.*.bar");

上面的示例启用了Option.REQUIRE_PROPERTIES配置选项,因此如果path不存在,它将抛出异常。

如何为MockMvc在春季启动项目中使用的jsonPath配置相同的东西?

import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
// ...
mockMvc
.perform(get("/test"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*.bar").isEmpty())  // How to configure this 'jsonPath'?

更新

请看下面的例子:

输入

[
{"animal": "cat", "meow": true},
{"animal": "cat", "meow": true},
{"animal": "cat", "bark": true}
]

表达
jsonPath("$.[?(@.animal == 'cat')].meow").value(everyItem(equalTo(true))

这会产生一个"假阳性"。测试的结果。我如何编写json路径表达式,因为我希望这个测试产生一个失败的结果。

不,不幸的是,我们不能在spring-test-mockmvc上下文中配置JSONPath那么好。

证明(https://github.com/spring-projects/spring-framework/blob/main/spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java # L61):

this.jsonPath = JsonPath.compile(this.expression);

"They"使用(内部)一个更简单的实例化(不需要配置)。

(isEmpty()有什么问题,需要这个例外吗?)还有其他的匹配器,比如:

  • doesNotExist()
  • doesNotHaveJsonPath()

如果我们需要这个精细的配置+精确的异常,我们仍然可以:

  • 直接使用JsonPath(/作为bean):
  • 解析(例如)从MvcResult.getResponse().getContentAsString()
@Bean
Configuration configuration()
return Configuration
.builder()
.options(Option.REQUIRE_PROPERTIES)
.build();
}

. .然后:

@Autowired
Configuration config;
// ...
MvcResult result = mockMvc
.perform(get("/test"))
.andExpect(status().isOk())
.andReturn();
// try/expect:
JsonPath
.using(config)
.parse(result.getResponse().getContentAsString())
.read("$.*.bar"); 

参:

  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/JsonPathResultMatchers.html
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/MvcResult.html
  • https://github.com/json-path/JsonPath (-/definit)

最新更新