简体   繁体   English

测试 Spring MVC 响应模式(忽略响应中项目中的 json 字段)

[英]Test Spring MVC response pattern (Ignore a json field in the items in the response )

I am testing a spring MVC application.我正在测试一个 spring MVC 应用程序。
I need to be sure that the response to the browser has a certain pattern, my application sends back some json, and for each Json item there is a field called DT_RowId that I do not want to compare, because DT_RowId contains a random number.我需要确保对浏览器的响应具有特定模式,我的应用程序发回一些 json,并且对于每个 Json 项目都有一个我不想比较的名为 DT_RowId 的字段,因为 DT_RowId 包含一个随机数。 Therefore, I would like to compare all the Json body, except DT_RowId and its content.因此,我想比较所有 Json 主体,除了 DT_RowId 及其内容。
By the way a typical occurence of DT_RowId is "DT_RowId":"8407709537703772".顺便说一句,DT_RowId 的典型出现是“DT_RowId”:“8407709537703772”。 And a typical json response is:典型的 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"}]}

Below, my test:下面,我的测试:

@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));
}

How can I modify the code above?如何修改上面的代码? I would like to compare all the Json response except the field"DT_RowId".我想比较除字段“DT_RowId”之外的所有 Json 响应。 Any clever ideas?有什么聪明的主意吗?

您可以使用andExpect(content()。matches(regex here)),并编写一个正则表达式来匹配您的users.getUsersJson.mywebapp.response.json内容(不包括DT_RowId)。

If you are willing to add an extra dependency to your project, this can be achieved using the JsonUnit Spring MVC integration and formatting your JSON as below如果您愿意向您的项目添加额外的依赖项,这可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM