membersound
membersound

Reputation: 86915

How to get ResponseBody of @RestController as object in a MockMvc junit test?

I have a simple junit test that verifies the response of a servlet endpoint.

Problem: I want to obtain the response as java object Person, and not as string/json/xml representation.

Is that possible?

@RestController
public class PersonController {
    @GetMapping("/person")
    public PersonRsp getPerson(int id) {
        //...
        return rsp;
    }   
}

@RunWith(SpringRunner.class)
@WebMvcTest(value = PersonController.class)
public class PersonControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        MvcResult rt = mvc.perform(get("/person")
                .param("id", "123")
                .andExpect(status().isOk())
                .andReturn();

        //TODO how to cast the result to (Person) p?
    }
}

Upvotes: 8

Views: 10567

Answers (3)

andgalf
andgalf

Reputation: 170

you could deserialize it like this:

String json = rt.getResponse().getContentAsString();
Person person = new ObjectMapper().readValue(json, Person.class);

You can also @Autowire the ObjectMapper

Upvotes: 11

membersound
membersound

Reputation: 86915

As my goal was mainly to test the whole setup, means by spring autoconfigured set of objectmapper and restcontroller, I just created a mock for the endpoint. And there returned the input parameter as response, so I can validate it:

@RestController
public class PersonControllerMock {
    @GetMapping("/person")
    public PersonDTO getPerson(PersonDTO dto) {
        return dto;
    }   
}


@RunWith(SpringRunner.class)
@WebMvcTest(value = PersonControllerMock.class)
public class PersonControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        mvc.perform(get("/person")
                .param("id", "123")
                .param("firstname", "john")
                .param("lastname", "doe")
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstname").value("john"))
                .andExpect(jsonPath("$.lastname").value("doe"))
                .andReturn();
    }
}

Upvotes: 2

Alexander.Furer
Alexander.Furer

Reputation: 1869

You can use TestRestTemplate::getForEntity if you are not limited with mockMvc

Upvotes: 0

Related Questions