如何不回滚@DataJpaTest?
How not to rollback @DataJpaTest?
在下面的代码中
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class GenreDaoJpaTest{
@Autowired
private TestEntityManager entityManager;
@Autowired
private GenreRepository dao;
....
}
当我添加 @Transactional(propagation = Propagation.NOT_SUPPORTED)
以在每次测试后取消回滚时,我遇到了异常:
ava.lang.IllegalStateException: No transactional EntityManager found
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.getEntityManager(TestEntityManager.java:237)
at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(TestEntityManager.java:92)
at ru.otus.ea.dao.GenreDaoJpaTest.init(GenreDaoJpaTest.java:38)
有没有办法在测试中自动装配 TestEntityManager
而不是回滚事务?
您的 TestEntityManager
是自动装配的,但您正在事务外执行 persist
调用。
你可以自动装配 TransactionTemplate
:
@Autowired
private TransactionTemplate transactionTemplate;
并使用其 execute
方法执行您的数据库交互:
User savedUser = transactionTemplate.execute((conn) -> {
return testEntityManager.persist(new User("foo"));
});
您还应该知道,现在您负责在测试执行后清理测试数据库(随着逻辑的增长,这可能很难维护):
@BeforeEach // just to be sure
@AfterEach
public void cleanup() {
userRepository.deleteAll();
}
在下面的代码中
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class GenreDaoJpaTest{
@Autowired
private TestEntityManager entityManager;
@Autowired
private GenreRepository dao;
....
}
当我添加 @Transactional(propagation = Propagation.NOT_SUPPORTED)
以在每次测试后取消回滚时,我遇到了异常:
ava.lang.IllegalStateException: No transactional EntityManager found
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.getEntityManager(TestEntityManager.java:237)
at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(TestEntityManager.java:92)
at ru.otus.ea.dao.GenreDaoJpaTest.init(GenreDaoJpaTest.java:38)
有没有办法在测试中自动装配 TestEntityManager
而不是回滚事务?
您的 TestEntityManager
是自动装配的,但您正在事务外执行 persist
调用。
你可以自动装配 TransactionTemplate
:
@Autowired
private TransactionTemplate transactionTemplate;
并使用其 execute
方法执行您的数据库交互:
User savedUser = transactionTemplate.execute((conn) -> {
return testEntityManager.persist(new User("foo"));
});
您还应该知道,现在您负责在测试执行后清理测试数据库(随着逻辑的增长,这可能很难维护):
@BeforeEach // just to be sure
@AfterEach
public void cleanup() {
userRepository.deleteAll();
}