Skip to content

Instantly share code, notes, and snippets.

@vdjurovic
Created September 8, 2015 08:14
Show Gist options
  • Save vdjurovic/01009ede2afd9348c9e9 to your computer and use it in GitHub Desktop.
Save vdjurovic/01009ede2afd9348c9e9 to your computer and use it in GitHub Desktop.
/**
* 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("user@mail.com");
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();
}
@scne
Copy link

scne commented Feb 7, 2017

How can I test if controller call an async service method like below?

CONTROLLER

@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<Void> userSignup(@RequestBody User user, HttpServletResponse response, HttpServletRequest request) {
            userService.createUser(user);
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(new URI("http://myhost.com/wlcome_page")));
            return new ResponseEntity<>(headers, HttpStatus.CREATED);
        }

SERVICE

@Async
    public Future<User> createUser(User user) Exception {
        user = userRepository.save(user);
        return new AsyncResult<>(user);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment