Spring:在单元测试中回滚事务。

huangapple go评论94阅读模式
英文:

Spring: Rollback transactin in Unittest

问题

我有一个复杂的服务方法,从数据库加载大量数据。由于它只读取和验证数据,我希望确保:

  1. JPA(Hibernate)不会浪费时间检查大的持久化上下文以进行更改。
  2. 不会意外将数据更改写入数据库。

因此,在我的服务末尾,我有这段代码:

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

  1. JPA (Hibernate) does not waste time for checking the big persistence
    context for changes.
  2. 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().

Doc

> A boolean flag that can be set to true if the transaction is effectively read-only, allowing for corresponding optimizations at runtime.

huangapple
  • 本文由 发表于 2020年9月11日 13:37:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63841316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定