如何在 Spring Boot 测试中强制事务提交? [英] How to force transaction commit in Spring Boot test?
问题描述
如何在 Spring Boot(使用 Spring Data)在运行方法时而不是在方法之后不强制事务提交?
How can I force a transaction commit in Spring Boot (with Spring Data) while running a method and not after the method ?
我在这里读到,在另一个类中使用 @Transactional(propagation = Propagation.REQUIRES_NEW)
应该是可能的,但对我不起作用.
I've read here that it should be possible with @Transactional(propagation = Propagation.REQUIRES_NEW)
in another class but doesn't work for me.
有什么提示吗?我使用的是 Spring Boot v1.5.2.RELEASE.
Any hints? I'm using Spring Boot v1.5.2.RELEASE.
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommitTest {
@Autowired
TestRepo repo;
@Transactional
@Commit
@Test
public void testCommit() {
repo.createPerson();
System.out.println("I want a commit here!");
// ...
System.out.println("Something after the commit...");
}
}
@Repository
public class TestRepo {
@Autowired
private PersonRepository personRepo;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void createPerson() {
personRepo.save(new Person("test"));
}
}
推荐答案
一种方法是在测试类中注入 TransactionTemplate
,删除 @Transactional
和 @Commit
并将测试方法修改为:
An approach would be to inject the TransactionTemplate
in the test class, remove the @Transactional
and @Commit
and modify the test method to something like:
...
public class CommitTest {
@Autowired
TestRepo repo;
@Autowired
TransactionTemplate txTemplate;
@Test
public void testCommit() {
txTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
repo.createPerson();
// ...
}
});
// ...
System.out.println("Something after the commit...");
}
或
new TransactionCallback<Person>() {
@Override
public Person doInTransaction(TransactionStatus status) {
// ...
return person
}
// ...
});
如果您打算向刚刚持久化的 person 对象添加断言,请不要使用 TransactionCallbackWithoutResult
回调实现.
instead of the TransactionCallbackWithoutResult
callback impl if you plan to add assertions to the person object that was just persisted.
这篇关于如何在 Spring Boot 测试中强制事务提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!