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?
}
}
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(); }
public interface MvcResult. Provides access to the result of an executed request.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With