NA.*_*NA. 95 java testing spring jsonpath spring-test-mvc
是否可以使用JsonPath计算成员数?
使用spring mvc test我正在测试一个生成的控制器
{"foo": "oof", "bar": "rab"}
Run Code Online (Sandbox Code Playgroud)
同
standaloneSetup(new FooController(fooService)).build()
.perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.foo").value("oof"))
.andExpect(jsonPath("$.bar").value("rab"));
Run Code Online (Sandbox Code Playgroud)
我想确保生成的json中没有其他成员.希望通过使用jsonPath计算它们.可能吗?也欢迎替代解决方案.
lop*_*san 207
要测试数组的大小:jsonPath("$", hasSize(4))
要计算对象的成员:jsonPath("$.*", hasSize(4))
即测试该API返回4个项目的数组:
接受价值: [1,2,3,4]
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$", hasSize(4)));
Run Code Online (Sandbox Code Playgroud)
测试该API返回一个包含2个成员的对象:
接受价值: {"foo": "oof", "bar": "rab"}
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
Run Code Online (Sandbox Code Playgroud)
我正在使用Hamcrest 1.3版和Spring Test 3.2.5.RELEASE
注意:您需要包含hamcrest-library依赖项以及import static org.hamcrest.Matchers.*;hasSize()才能工作.
sta*_*let 17
您还可以使用 jsonpath 中的方法,而不是
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
Run Code Online (Sandbox Code Playgroud)
你可以做
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.length()", is(2)));
Run Code Online (Sandbox Code Playgroud)
我们可以使用JsonPath功能像size()或者length(),就像这样:
@Test
public void givenJson_whenGetLengthWithJsonPath_thenGetLength() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
int length = JsonPath
.parse(jsonString)
.read("$.length()");
assertThat(length).isEqualTo(3);
}
Run Code Online (Sandbox Code Playgroud)
或者只是解析net.minidev.json.JSONObject并获取大小:
@Test
public void givenJson_whenParseObject_thenGetSize() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
assertThat(jsonObject)
.size()
.isEqualTo(3);
}
Run Code Online (Sandbox Code Playgroud)
实际上,第二种方法看起来比第一种方法表现更好。我进行了JMH性能测试,并得到以下结果:
| Benchmark | Mode | Cnt | Score | Error | Units |
|-------------------------------------------------|-------|-----|-------------|--------------|-------|
| JsonPathBenchmark.benchmarkJSONObjectParse | thrpt | 5 | 3241471.044 | ±1718855.506 | ops/s |
| JsonPathBenchmark.benchmarkJsonPathObjectLength | thrpt | 5 | 1680492.243 | ±132492.697 | ops/s |
Run Code Online (Sandbox Code Playgroud)
示例代码可以在这里找到。
| 归档时间: |
|
| 查看次数: |
60365 次 |
| 最近记录: |