如何在 Spring Boot 测试中强制事务提交? [英] How to force transaction commit in Spring Boot test?

查看:133
本文介绍了如何在 Spring Boot 测试中强制事务提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆