使用@Async方法的java JUnit回滚事务
我正在使用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();
}
在流程的最后,一个实体被保存到数据库中。但这里的要求是,应该异步完成。所以认为这种方法叫做:
@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建议它应该以这种方式工作,但对我来说,测试后不会进行回滚李> - 交换这两个注释的位置。它也不能给出预期的结果李>
有人知道如何强制回滚异步方法中的DB更改吗
旁注:
事务配置:
<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"/>
# 1 楼答案
不幸的是,这是不可能的
Spring通过
ThreadLocal
变量管理事务状态。因此,在另一个线程中启动的事务(例如,为@Async
方法调用创建的事务)可以不参与为父线程管理的事务这意味着
@Async
方法使用的事务与test-managed transaction相同,后者由Spring TestContext框架自动回滚因此,解决问题的唯一可能方法是手动撤消对数据库的更改。您可以使用
JdbcTestUtils
在@AfterTransaction
方法中以编程方式执行SQL脚本,也可以通过Spring的@Sql
注释(使用after执行阶段)以声明方式配置SQL脚本。关于后者,请参见How to execute @Sql before a @Before method了解详细信息问候
Sam(Spring TestContext框架的作者)