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

Spring MVC Integration Testing

Spring MVC Integration Testing

Slides of my talk about the Spring MVC integration testing framework held at JUG Saxony Day 2014 in Dresden.

@springcentral

Oliver Drotbohm

April 04, 2014
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 Controller
  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. Test Context Framework ! ! ! ! ! ! !

    ApplicationContext MockMVC ! ! !
  4. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration("classpath:application-context.xml") public class SampleIntegrationTests { ! @Autowired WebApplicationContext

    context; MockMvc mvc; ! @Before public void setUp() { this.mvc = MockMvcBuilders. webAppContextSetup(this.context).build(); } } MVC testing
  5. import static org.sfw.….MockMvcRequestBuilders.*; import static org.sfw.….MockMvcResultMatchers.*; ! public class SampleIntegrationTests

    { ! @Before 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
  6. 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