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

时间:2013-08-27 10:40:33

标签: java json spring spring-mvc junit

我正在测试一个spring MVC应用程序。
我需要确保对浏览器的响应有一定的模式,我的应用程序发回一些json,并且每个Json项目都有一个名为DT_RowId的字段我不想比较,因为DT_RowId包含一个随机数。因此,我想比较除了DT_RowId及其内容之外的所有Json主体。
顺便说一下,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响应。任何聪明的想法?

1 个答案:

答案 0 :(得分:0)

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