Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map mock mvc GET call into java POJO?

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.

like image 857
ITWorker Avatar asked Feb 06 '17 16:02

ITWorker


Video Answer


1 Answers

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);
like image 132
Justinas Jakavonis Avatar answered Sep 28 '22 08:09

Justinas Jakavonis