Created
September 8, 2015 08:14
-
-
Save vdjurovic/01009ede2afd9348c9e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Spring controller method using async features.Controller method to handle POST.requests. It will set 'Location' header and set HTTP status to 201. | |
*/ | |
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) | |
public Callable<ResponseEntity<Void>> userSignup(@RequestBody User user, HttpServletResponse response, HttpServletRequest request) { | |
return () -> { | |
String id = userService.createUser(user); | |
HttpHeaders headers = new HttpHeaders(); | |
headers.setLocation(new URI("http://myhost.com/users/id/" + id))); | |
return new ResponseEntity<>(headers, HttpStatus.CREATED); | |
}; | |
} | |
/** | |
* Test case for the method above. It uses SPring MockMvc for controller testing. | |
*/ | |
@Test | |
public void createUserTest() throws Exception{ | |
User user = new User(); | |
user.setFirstname("John"); | |
user.setLastname("Doe"); | |
user.setEmail("[email protected]"); | |
user.setPassword("password"); | |
JAXBContext ctx = JAXBContext.newInstance(User.class); | |
Marshaller marshaller = ctx.createMarshaller(); | |
StringWriter writer = new StringWriter(); | |
marshaller.marshal(user, writer); | |
writer.close(); | |
System.out.println("XML: " + writer.toString()); | |
MvcResult result = mockMvc.perform(post("/users").content(writer.toString()).contentType("application/xml")).andExpect(request().asyncStarted()).andReturn(); | |
mockMvc.perform(asyncDispatch(result)).andExpect(status().isCreated()).andExpect(header().string("Location",org.hamcrest.Matchers.startsWith("http://localhost:80/users/id"))).andDo(print()).andReturn(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can I test if controller call an async service method like below?
CONTROLLER
SERVICE