Search code examples
jsonspringspring-mvcjunit

Is there a method built in spring MockMVC to get json content as Object?


In my Spring project i created some tests that check the controllers/ http-api. Is there a way to get the json content of response as de-serialized object?

In other project i used rest assured and there methods to acquire results directly as expected objects.

Here is an example:

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

            .andExpect( status().is( HttpStatus.OK.value() ) ).andReturn();
    String string = result.getResponse().getContentAsString();

The method returns a specific type as json. how to convert this json back to an object to tests its contents? I know ways with jackson or with rest-assured but is there a way within spring/test/mockmvc

Like getContentAs(Class)


Solution

  • As far as I know MockHttpServletResponse (Unlike RestTemplate) doesn't have any method which could convert returned JSON to a particular type.

    So what you could do is use Jackson ObjectMapper to convert JSON string to a particular type

    Something like this

    String json = rt.getResponse().getContentAsString();
    SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);
    

    This will give you more control for you to assert different things.

    Having said that, MockMvc::perform returns ResultActions which has a method andExpect which takes ResultMatcher. This has a lot of options to test the resulting json without converting it to an object.

    For example

    mvc.perform(  .....
                    ......
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.firstname").value("john"))
                    .andExpect(jsonPath("$.lastname").value("doe"))
                    .andReturn();