首页 > 解决方案 > 从 grails 2.3.4 迁移到 3.3.8 时无法模拟域

问题描述

我有一个名为 Provenance 的域类,用于标记应用程序创建的记录与其他创建方法(ETL 等)。记录预先存在于数据库中,并且 beforeInsert、beforeUpdate、beforeDelete 抛出 RuntimeException 以强制域为只读

class Provenance implements Serializable {
    ...
    static Provenance MANUAL() {
        findByProvenanceType('MANUAL')
    }

    def beforeInsert() {
        throw new RuntimeException('create not allowed')
    }
    ...
}

我正在测试一种保存 Person (mockDomain) 记录的服务方法。我曾经这样嘲笑过:

given:
def provenance = GroovyMock(Provenance, global: true)
...
when:
def result = service.savePerson(params)
...
then:
1 * Provenance.MANUAL() >> provenance
result.person.provenance == provenance

迁移的主要变化是 2.3.4 使用 @Mock 用于 Person 域,而 mockDomain 用于 3.3.8。

这适用于 grails 2.3.4。但是当迁移到 grails 3.3.8 时,将人员级联到 Provenance,这会导致从 beforeInsert 中抛出 RuntimeException。

我还考虑过在 Provenance 上使用 mockDomain 并预先保存它,但我有同样的问题,因为 beforeInsert 不能被覆盖以防止 RuntimeException。关于为什么这会在版本之间发生变化以及如何解决它的任何想法?

标签: grailsmockinggrails-ormgeb

解决方案


根据 ice1080 在 Overriding eventclosure on Grails GORM domain class for unit testing中的建议,我将 beforeInsert 中的逻辑移至另一个方法并在测试中覆盖该方法以允许在设置期间创建域


推荐阅读