13

I have a rest controller method that returns an object CompositeObject that contains within it several other objects and structures (Maps and Lists). I want to write a test that tests whether the rest get call returns that object along with the fields (even if the values for those fields are null), but I don't know how to map the response of the mock mvc call below:

String response = this.mockMvc.perform(get("/getclassdata?classCode=cs").accept("application/json"))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();

This test works fine, however I want to check whether the returned JSON is an object I am interested in (CompositeObject) as well as make sure that it contains all the required fields. How can I test for this? Is there something in the testing framework that is similar to instanceof?

Thank you.

ITWorker
  • 965
  • 2
  • 16
  • 39

1 Answers1

13

You can read Json response to POJO using com.fasterxml.jackson.databind.ObjectMapper:

ObjectMapper mapper = new ObjectMapper();

MvcResult mvcResult = mockMvc.perform(get("/example-endpoint")).andReturn();

ExampleResponse parsedResponse = mapper.readValue(mvcResult.getResponse().getContentAsByteArray(), ExampleResponse.class);
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114