[英]Test Spring MVC response pattern (Ignore a json field in the items in the response )
我正在测试一个 spring MVC 应用程序。
我需要确保对浏览器的响应具有特定模式,我的应用程序发回一些 json,并且对于每个 Json 项目都有一个我不想比较的名为 DT_RowId 的字段,因为 DT_RowId 包含一个随机数。 因此,我想比较所有 Json 主体,除了 DT_RowId 及其内容。
顺便说一句,DT_RowId 的典型出现是“DT_RowId”:“8407709537703772”。 典型的 json 响应是:
{"id":-1,"fieldErrors":[],"aaData":[{"id":8002,"firstname":"Bob","lastname":"Jones","email":"bob.jones@gmail.com","DT_RowId":"8407709537703772"},{"id":8002,"firstname:"Dan","lastname":"Jones","email":"dan.jones@gmail.com","DT_RowId":"8404309537701754"}]}
下面,我的测试:
@Test
public void testGetUsersJson() throws Exception {
mockMvc.perform(get("/users")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentType("application/json"))
// How can I modify the line below??
.andExpect(content().bytes(IOUtils.toByteArray(ctx.getResource("classpath:responses/users.getUsersJson.mywebapp.response.json").getInputStream())))
.andExpect(status().isOk())
.andExpect(redirectedUrl(null))
.andExpect(forwardedUrl(null));
}
如何修改上面的代码? 我想比较除字段“DT_RowId”之外的所有 Json 响应。 有什么聪明的主意吗?
您可以使用andExpect(content()。matches(regex here)),并编写一个正则表达式来匹配您的users.getUsersJson.mywebapp.response.json内容(不包括DT_RowId)。
如果您愿意向您的项目添加额外的依赖项,这可以使用JsonUnit Spring MVC 集成和格式化您的 JSON 来实现,如下所示
{
"id": -1,
"fieldErrors": [],
"aaData": [
{
"id": 8002,
"firstname": "Bob",
"lastname": "Jones",
"email": "bob.jones@gmail.com",
"DT_RowId": "${json-unit.any-number}"
},
{
"id": 8002,
"firstname": "Dan",
"lastname": "Jones",
"email": "dan.jones@gmail.com",
"DT_RowId": "${json-unit.any-number}"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.