我最近升级到 Grails 2.3 并尝试将所有旧测试迁移到 spock 集成测试。但它在清理时失败,因为我的测试是非事务性的。 Grails 文档说测试可以是非事务性的,但我们需要手动处理它,但在这里似乎不太合适。因为我在每个扩展 IntegrationSpec 的集成测试中都收到此错误
java.lang.IllegalStateException: Cannot deactivate transaction synchronization - not active
at grails.test.spock.IntegrationSpec.cleanup(IntegrationSpec.groovy:72)
像这样的简单测试会抛出该错误:
import grails.test.spock.IntegrationSpec
public class DummySpec extends IntegrationSpec {
static transactional = false
def setup() {
}
def cleanup() {
}
def testDummy() {
expect:
1 == 1
}
}
最佳答案
我也遇到了这个!很确定它是一个 grails 错误...我提交了一个 jira和一个 patch .
抛出错误是因为 grails.test.spock.IntegrationSpec 中的代码没有检查 interceptor.isTransactional()
调用前 interceptor.destroy()
def cleanup() {
perMethodRequestEnvironmentInterceptor?.destroy()
perMethodTransactionInterceptor?.destroy() //breaks :(
}
...
private GrailsTestTransactionInterceptor initTransaction() {
def interceptor = new GrailsTestTransactionInterceptor(applicationContext)
if (interceptor.isTransactional(this)) interceptor.init() //also need for destroy()
interceptor
}
我的解决方法是添加以下代码:
def cleanup() {
perMethodRequestEnvironmentInterceptor?.destroy()
destroyTransaction(perMethodTransactionInterceptor)
}
...
private void destroyTransaction(GrailsTestTransactionInterceptor interceptor){
if (interceptor?.isTransactional(this)) interceptor.destroy()
}
要暂时解决这个问题,您可以使用修补过的代码创建自己的 com.myname.IntegrationSpec 并扩展它而不是 grails.test.spock.IntegrationSpec。不理想......但它有效:)
关于Grails 2.3 IntegrationSpec 不能是事务性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20389973/