我正在用 MockMvc 做一些测试,我想验证 JSON 响应的结构。具体来说,我想确保属性的键存在,并且该值是某种类型或 null。
{
"keyToNull": null, # This may be null, or a String
"keyToString": "some value"
}
以下对我有用,但我想知道是否有办法将每组两个期望组合成一行,因为我有很多属性要检查:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;
.andExpect(jsonPath("$").value(hasKey("keyToNull")))
.andExpect(jsonPath("$.keyToNull").value(
anyOf(any(String.class), nullValue(String.class))))
.andExpect(jsonPath("$").value(hasKey("keyToString")))
.andExpect(jsonPath("$.keyToString").value(
anyOf(any(String.class), nullValue(String.class))))
这hasKey()
是必要的,因为其他断言本身通过,因为 MockMvc 的实现中不存在的键映射为 null:
.andExpect(jsonPath("$.notAKey").value(
anyOf(any(String.class), nullValue(String.class)))) // ok
jsonPath().exists()
也不起作用,因为它在内部将值与null
.
我考虑过制作这样的单独方法:
private static <T> void assertNullableAttr(ResultActions res, String jsonPath, Class<T> type) throws Exception {
int split = jsonPath.lastIndexOf('.');
String prefix = jsonPath.substring(0, split), key = jsonPath.substring(split+1);
res.andExpect(jsonPath(prefix).value(hasKey(key)))
.andExpect(jsonPath(jsonPath).value(anyOf(any(type), nullValue(type))));
}
但它迫使我以一种不自然的方式拆分我的代码:
ResultActions res = mockMvc.perform(get("/api"))
// these attributes must not be null
.andExpect(jsonPath("$.someInfo").value(hasSize(2)))
.andExpect(jsonPath("$.someInfo[0].info1").value(any(String.class)))
.andExpect(jsonPath("$.someInfo[0].info2").value(any(String.class)))
.andExpect(jsonPath("$.addlInfo").value(hasSize(2)))
.andExpect(jsonPath("$.addlInfo[0].info1").value(any(String.class)))
.andExpect(jsonPath("$.addlInfo[0].info2").value(any(String.class)));
// these attributes may be null
assertNullableAttr(res, "$.someInfo[0].info3", String.class);
assertNullableAttr(res, "$.someInfo[0].info4", String.class);
assertNullableAttr(res, "$.addlInfo[0].info3", String.class);
assertNullableAttr(res, "$.addlInfo[0].info4", String.class);
是否有任何聪明的 Hamcrest Matcher 可以应用于每个属性的单个 json 路径?