我正在使用SpringJUnit4ClassRunner
. 我有一个基类:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ /*my XML files here*/})
@Ignore
public class BaseIntegrationWebappTestRunner {
@Autowired
protected WebApplicationContext wac;
@Autowired
protected MockServletContext servletContext;
@Autowired
protected MockHttpSession session;
@Autowired
protected MockHttpServletRequest request;
@Autowired
protected MockHttpServletResponse response;
@Autowired
protected ServletWebRequest webRequest;
@Autowired
private ResponseTypeFilter responseTypeFilter;
protected MockMvc mockMvc;
@BeforeClass
public static void setUpBeforeClass() {
}
@AfterClass
public static void tearDownAfterClass() {
}
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(responseTypeFilter).build();
}
@After
public void tearDown() {
this.mockMvc = null;
}
}
然后我扩展它并使用 mockMvc 创建一个测试:
public class MyTestIT extends BaseMCTIntegrationWebappTestRunner {
@Test
@Transactional("jpaTransactionManager")
public void test() throws Exception {
MvcResult result = mockMvc
.perform(
post("/myUrl")
.contentType(MediaType.APPLICATION_XML)
.characterEncoding("UTF-8")
.content("content")
.headers(getHeaders())
).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(content().encoding("ISO-8859-1"))
.andExpect(xpath("/*[local-name() ='myXPath']/")
.string("result"))
.andReturn();
}
在流程结束时,将实体保存到 DB 中。但这里的要求是应该异步完成。所以考虑调用这个方法:
@Component
public class AsyncWriter {
@Autowired
private HistoryWriter historyWriter;
@Async
public void saveHistoryAsync(final Context context) {
History history = historyWriter.saveHistory(context);
}
}
然后HistoryWriter
被称为:
@Component
public class HistoryWriter {
@Autowired
private HistoryRepository historyRepository;
@Transactional("jpaTransactionManager")
public History saveHistory(final Context context) {
History history = null;
if (context != null) {
try {
history = historyRepository.saveAndFlush(getHistoryFromContext(context));
} catch (Throwable e) {
LOGGER.error(String.format("Cannot save history for context: [%s] ", context), e);
}
}
return history;
}
}
所有这一切的问题是,在测试完成后,History
对象留在数据库中。我需要进行测试事务以最终回滚所有更改。
现在,到目前为止我已经尝试过:
- 删除
@Async
注释。显然,这不是解决方案,而是为了确认没有它的情况下将执行回滚。它的确是。 - 将
@Async
注释移动到HistoryWriter.saveHistory()
方法以将其与@Transactional
. 这篇文章https://dzone.com/articles/spring-async-and-transaction建议它应该以这种方式工作,但对我来说,测试后没有回滚。 - 交换这两个注释的位置。它也没有给出预期的结果。
有谁知道如何强制回滚异步方法中所做的数据库更改?
旁注:
交易配置:
<tx:annotation-driven proxy-target-class="true" transaction- manager="jpaTransactionManager"/>
异步配置:
<task:executor id="executorWithPoolSizeRange" pool-size="50-75" queue-capacity="1000" />
<task:annotation-driven executor="executorWithPoolSizeRange" scheduler="taskScheduler"/>