在Spring MockMVC中有内置的方法来获取json内容作为Object吗?

der*_*itz 8 junit spring json spring-mvc

在我的Spring项目中,我创建了一些检查控制器/ http-api的测试。有没有办法获取响应的json内容作为反序列化对象?

在其他项目中,我使用了放心的方法,并且有方法直接将结果作为预期的对象来获取。

这是一个例子:

    MvcResult result = rest.perform( get( "/api/byUser" ).param( "userName","test_user" ) )

            .andExpect( status().is( HttpStatus.OK.value() ) ).andReturn();
    String string = result.getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)

该方法返回特定类型的json。如何将此json转换回对象以测试其内容?我知道杰克逊的方法或放心的方法,但是在spring / test / mockmvc中有办法吗

喜欢 getContentAs(Class)

pvp*_*ran 11

据我所知MockHttpServletResponse(与RestTemplate不同),没有任何方法可以将返回的json转换为特定类型,
所以您可以使用Jakson ObjectMapper将json字符串转换为特定类型

像这样

String json = rt.getResponse().getContentAsString();
SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);
Run Code Online (Sandbox Code Playgroud)

这将使您拥有更多控制权来主张不同的事情。

话虽如此,MockMvc::perform回报ResultActions有一个andExpect采取的方法ResultMatcher。这有很多选项可以测试结果json,而无需将其转换为对象。

例如

mvc.perform(  .....
                ......
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstname").value("john"))
                .andExpect(jsonPath("$.lastname").value("doe"))
                .andReturn();
Run Code Online (Sandbox Code Playgroud)

  • 尽管这可行,但它会创建一个新的 ObjectMapper 实例,该实例可能与配置的实例不同。您可能最好注入 Spring Boot 创建的一个。 (2认同)