Spring MockMvc异步测试不会回滚

时间:2015-09-06 08:45:57

标签: java spring spring-mvc

我试图将Spring REST Controller转换为异步模式,但我在使用MockMvc运行测试时遇到问题。测试通过,但它不会回滚DB更改,因此我最终得到了DB中的测试数据。使用同步控制器时,数据会正确回滚。

这是我的控制器方法:

@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(findServerUrlFromRequest(request, "/users/id/" + id)));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    };

}

这是测试:

 @Test
@Rollback(true)
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();

}

我认为它存在某种配置问题,但无法弄清问题是什么。任何人都可以给我一个暗示吗?

0 个答案:

没有答案