Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
    }
}
like image 810
membersound Avatar asked Nov 09 '17 14:11

membersound


People also ask

What is MockMvc in JUnit?

MockMvc provides support for Spring MVC testing. It encapsulates all web application beans and makes them available for testing. Let's see how to use it: private MockMvc mockMvc; @BeforeEach public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); }

What is MvcResult?

public interface MvcResult. Provides access to the result of an executed request.


1 Answers

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

like image 58
andgalf Avatar answered Oct 05 '22 19:10

andgalf