如何在Spring Boot测试中强制事务提交?

如何在运行方法时在Spring Boot(使用Spring Data)中强制提交事务,而不是在方法之后?

我在这里读到过,它应该可以在另一个班级中使用,但对我不起作用。@Transactional(propagation = Propagation.REQUIRES_NEW)

任何提示?我正在使用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"));
    }
}

答案 1

使用帮助程序类(从 Spring 4.1 开始)。org.springframework.test.context.transaction.TestTransaction

默认情况下,测试将回滚。要真正承诺一个人需要做

// do something before the commit 

TestTransaction.flagForCommit(); // need this, otherwise the next line does a rollback
TestTransaction.end();
TestTransaction.start();

// do something in new transaction

答案 2

一种方法是在测试类中注入,删除 and 并将测试方法修改为如下所示:TransactionTemplate@Transactional@Commit

...
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
    }

    // ...
});

而不是回调 impl,如果您计划向刚刚保留的 person 对象添加断言。TransactionCallbackWithoutResult


推荐