英文:
Spring: Rollback transactin in Unittest
问题
我有一个复杂的服务方法,从数据库加载大量数据。由于它只读取和验证数据,我希望确保:
- JPA(Hibernate)不会浪费时间检查大的持久化上下文以进行更改。
- 不会意外将数据更改写入数据库。
因此,在我的服务末尾,我有这段代码:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
我的单元测试中为所有数据库访问提供了模拟,因此事务不是问题。(我还有带有@SpringBootTest
的集成测试,并且也完全支持事务。)不幸的是,回滚语句在纯单元测试中失败了。
在单元测试的情况下,有没有一种简单的方法让回滚语句什么都不做?
英文:
I have a complex service method, that loads a lot of data from the db. Since it only reads and validates data I want to make sure
- JPA (Hibernate) does not waste time for checking the big persistence
context for changes. - No accidental changes to the data are written
to the db.
Therefore towards the end of my service I have this code
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
My unit tests have mocks for all db access, so transactioning is not an issue. (I have integration test with @SpringBootTest
and full trx support as well.) Unfortunately the rollback statement fails in pure unit tests.
Is there an easy way to get the rollback statement just do nothing in case of a unit test?
答案1
得分: 0
现在我只是写了一个简单的组件,很容易进行模拟:
@Component
public class RollBacker {
public void setRollBackOnly() {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
毕竟,正是TransactionAspectSupport
的单例方法使得这里的单元测试变得困难。我个人认为TransactionAspectSupport
应该是一个Spring Bean。
英文:
For now I just wrote a small component which is easy to mock:
@Component
public class RollBacker {
public void setRollBackOnly() {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
After all it's the singleton approach of TransactionAspectSupport
which makes unit testing difficult here. IMHO TransactionAspectSupport
should be a spring bean.
答案2
得分: -1
请考虑使用 @Transactional(readOnly=true)
,而不是 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
。
一个布尔标志,如果事务实际上是只读的,可以将其设置为true,在运行时可以进行相应的优化。
英文:
Consider to use @Transactional(readOnly=true)
instead of TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
.
> A boolean flag that can be set to true if the transaction is effectively read-only, allowing for corresponding optimizations at runtime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论