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)
MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases which tests REST controller methods written for Spring boot 2 hateoas example.
standaloneSetup() allows to register one or more controllers without the need to use the full WebApplicationContext . @Test public void testHomePage() throws Exception { this.mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andDo(MockMvcResultHandlers.print()); }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With