每次使用Spring Boot回滚黄瓜场景后的事务



我正在使用BDD测试框架Cucumber with Spring Boot 2.5。我想在每个Cucumber场景之后回滚事务或重置数据库。我使用H2数据库,由动态生成的数据填充。我试过@Transactional,但它不起作用,@DirtiesContext也很慢。

这样做的方法是在每个场景之前使用PlatformTransactionManager启动事务,并在之后回滚它。这实际上是TransactionalTestExecutionListener在执行带有@Transactional注释的JUnit测试类时所做的工作。

在Cucumber中,您将使用@Before@After钩子来执行此操作。因为你可能不想对每个场景都这样做,所以你可以选择使钩子有条件,这样它们只在场景以正确的方式标记时执行。

例如:

@txn
Feature: Search
Background:
Given there is a user
Scenario: Find messages by content
Given a User has posted the following messages:
| content            |
| I am making dinner |
| I just woke up     |
| I am going to work |
When I search for "I am"
Then the results content should be:
| I am making dinner |
| I am going to work |
public class SpringTransactionHooks implements BeanFactoryAware {
private BeanFactory beanFactory;
private TransactionStatus transactionStatus;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Before(value = "@txn", order = 100)
public void startTransaction() {
transactionStatus = beanFactory.getBean(PlatformTransactionManager.class)
.getTransaction(new DefaultTransactionDefinition());
}

@After(value = "@txn", order = 100)
public void rollBackTransaction() {
beanFactory.getBean(PlatformTransactionManager.class)
.rollback(transactionStatus);
}
}

来自:

https://github.com/cucumber/cucumber-jvm/tree/main/examples/spring-java-junit5

相关内容

  • 没有找到相关文章

最新更新