【发布时间】:2015-05-06 13:33:25
【问题描述】:
简单来说,我有以下场景:
class OwnedRights {
static belongsTo = [comp: Competition]
@Transactional
def afterInsert() {
// Erroring out here.
Event.findAllByComp(comp).each { event ->
// Do something with event.
}
}
}
当我尝试使用以下内容保存单元测试时:
def ownedRights = new OwnedRights(params).save(flush: true, failOnError: true)
我看到以下堆栈跟踪:
java.lang.NullPointerException 在 org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130) 在 org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85) 在 org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:209) 在 org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:194)
这导致我转到this Jira Issue,这表明我没有使用@Mock 注释,但是在我的测试中,我正在模拟所有使用的域类:
@Mock([OwnedRights, Sport, Competition, Event])
这是包含 GORM 逻辑的休眠事件的已知问题吗?
尝试解决
我已尝试使用元类覆盖 afterInsert() 和 beforeDelete 方法:
OwnedRights.metaClass.afterInsert = null;
OwnedRights.metaClass.beforeDelete = null;
和
OwnedRights.metaClass.afterInsert = {};
OwnedRights.metaClass.beforeDelete = {};
两者都对结果没有影响。如果我注释掉 afterInsert 事件,保存就完美了。
【问题讨论】:
标签: unit-testing grails mocking spock