我在通过以下方式回滚服务层中的事务时遇到问题:
Grails 3.3.8
GORM 6.1.10。发布
我有以下服务方法:
val-*
我还创建了以下集成测试:
import grails.gorm.transactions.Transactional
@Transactional(rollbackFor = Exception.class)
class TestingService {
void testServiceMethod(List<Factory> factories) {
try {
factories.each {
if (it.name == 'second') {
throw new Exception('second')
}
it.testField = 'Edited'
it.save()
println(it.name + ' saved')
}
} catch (Exception e) {
println('Exception Caught ' + e)
}
}
}
我还有以下控制器方法:
@Integration
@Rollback
class TestServiceIntSpec extends Specification {
@Autowired
TestingService testingService
def setup() {
}
def cleanup() {
}
void "test something"() {
when:
Factory factoryOne = new Factory(name: "first").save(flush: true)
Factory factoryTwo = new Factory(name: "second").save(flush: true)
List<Factory> factories = [factoryOne, factoryTwo]
testingService.testServiceMethod(factories)
then:
factoryOne.testField == null
factoryTwo.testField == null
}
}
我本来希望测试通过,因为我认为在抛出新异常后事务将回滚,但是it.testField仍然存在吗?另外,当我对TestController进行ping操作时,它会将factoryOne.testField输出为“已编辑”。我是否从文档中正确地理解了这一点?
“服务启用事务划分,这是定义要使哪些方法具有事务性的声明方式。要在服务上启用事务,请使用事务转换: 结果是所有方法都包装在事务中,并且如果方法抛出异常(Checked或Runtime异常)或错误,则会发生自动回滚。“
来源:https://docs.grails.org/latest/guide/services.html#declarativeTransactions
我也看不出自己在做什么与其他Stackoverflow答案不同:
https://stackoverflow.com/a/25739582/6887293
可以通过拉出以下Github项目并运行/factory/factory/src/integration-test/groovy/com/mycompany/myapp/TestServiceIntSpec.groovy或ping / factory / factory / grails-app / controllers来重新创建此问题/com/mycompany/myapp/TestController.groovy
https://github.com/georgy3k/IntegrationTestRollBack/tree/8addd2b95a8ffa4570e70eccb3b023b0ccfef5aa
预先感谢...
答案 0 :(得分:0)
在您的catch块中,您需要重新引发异常。
catch (Exception e) {
println('Exception Caught ' + e)
throw e;
}
我所看到的问题是,异常永远不会逃脱方法。