Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Spring MVC Integration Testing

Spring MVC Integration Testing

Slide of my talk at JUG Ostfalen about Spring MVC integration testing

Oliver Drotbohm

August 15, 2013
Tweet

More Decks by Oliver Drotbohm

Other Decks in Programming

Transcript

  1. @Controller class PersonController { @RequestMapping(value = "/people", method = GET)

    HttpEntity<List<Person>> showPeople() { List<Person> result = people.findAll(); return new ResponseEntity<>(result, HttpStatus.OK); } @RequestMapping(value = "/people", method = POST) HttpEntity<Void> create(@RequestBody Person person) { Person result = people.create(person); HttpHeaders = new HttpHeaders(); headers.setLocation(…); return new ResponseEntity<>(headers, HttpStatus.CREATED); } } REST
  2. @Controller class PersonController { @RequestMapping(value = "/people", method = GET)

    String showPeople(Model model) { model.put("people", people.findAll()); return "people"; } @RequestMapping(value = "/people", method = POST) String create(@ModelAttribute Person person, Model model) { Person result = people.create(person); // Add success or error message to model return "people"; } } View resolution
  3. import static org.sfw.….MockMvcRequestBuilders.*; import static org.sfw.….MockMvcResultMatchers.*; public class SampleIntegrationTests {

    @Test public void setUp() { this.mvc.perform(get("/accounts/1") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.name").value("Lee")); } } MVC testing
  4. import static org.sfw.….MockRestResponseCreators.*; RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer

    = MockRestServiceServer.createServer(restTemplate); mockServer.expect(requestTo("/greeting")) .andRespond(withSuccess("Hello world!", "text/plain")); // use RestTemplate mockServer.verify(); Mock REST server