gpt4 book ai didi

Spring集成测试与手动事务管理

转载 作者:行者123 更新时间:2023-12-03 12:11:00 26 4
gpt4 key购买 nike

我已经阅读了许多关于 Spring 集成测试的帖子和主题,但没有任何内容令人满意或有帮助。

我们将 Spring 3.2.3 与 Hibernate、Spring Data 和 Oracle 数据库一起使用。对于测试,我们还使用 DbUnit 和 Spring-test-dbunit。在生产代码中,事务由 Controller 启动,服务本身对事务一无所知。

所以,这是我的测试:

@ContextConfiguration // ...
@ActiveProfiles // ...
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
ModifiedDbUnitTestExecutionListener.class })
@DbUnitConfiguration(databaseConnection = "oracleConnection")
@DatabaseSetup("/database/snapshot/snapshot.xml")
public class IntegrationTest extends AbstractTransactionalJUnit4SpringContextTests
{
@Test
public void sampleTest()
{
// transaction is already started

this.assertThatNewsContains(0);

News news1 = new News();
news1.setTitle("Test News 1");
News savedNews1 = this.newsService.save(news1);
Assert.assertTrue(savedNews1.getId() > 0);

News news2 = new News();
news2.setTitle("Test News 2");
News savedNews2 = this.newsService.save(news2);
Assert.assertTrue(savedNews2.getId() > 0);

News news3 = new News();
news3.setTitle("Test News 3");
News savedNews3 = this.newsService.save(news3);
Assert.assertTrue(savedNews3.getId() > 0);

// transaction commit should occur HERE
// @todo: HOW ?!

this.assertThatNewsContains(3);
}

private void assertThatNewsContains(int newsSize)
{
List<News> allNews = this.newsService.getNews();
Assert.assertEquals(newsSize, allNews.size());
}

}

我发现的是,如果我用 @Transactional(propagation=Propagation.REQUIRES_NEW) 注释 NewsService测试工作正常,但与生产模式不同。 @Transactional(propagation=Propagation.REQUIRED)是不够的,因为 DbUnit-Spring-test 自己打开一个事务,而后者断言失败,因为该事务尚未提交。如何在执行最后一个断言之前提交事务?

最佳答案

我终于设法在单独的事务中执行了一些代码。

你需要

@Autowired
private PlatformTransactionManager platformTransactionManager;

private TransactionTemplate transactionTemplate;

在你的测试课上。然后您可以执行以下操作:
this.transactionTemplate = new TransactionTemplate(this.platformTransactionManager);

// note that parameters passed to the transaction must be final!
final Object parameter = something;

Object returnedValue = this.transactionTemplate.execute(new TransactionCallback<Object>()
{
@Override
public Object doInTransaction(TransactionStatus status)
{
return doSomethingAndReturnAnObject(parameter);
}
}
);

关于Spring集成测试与手动事务管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31914827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com