8

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?
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

11

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

lilalinux
  • 2,903
  • 3
  • 43
  • 53
andgalf
  • 170
  • 10
2

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();
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
0

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

Alexander.Furer
  • 1,817
  • 1
  • 16
  • 24