Grails:Spock:单元测试 GORM 域 class 钩子

Grails : Spock : Unit testing GORM domain class hooks

通常我通过为约束和任何自定义方法(由我们在应用程序中创建)编写测试用例来结束为域编写测试用例,因为我们知道我们不应该测试明显的。

但是当我们开始使用覆盖插件时,我们发现我们的域代码行没有被完全覆盖,这是由于我们从未为其编写测试用例的 gorm hooks(onInsert, beforeUpdate)。

我们有办法测试这些吗?一种看似明显但不合适的可能方法是在这些钩子中调用另一个方法(包含钩子中较早的所有代码)并仅测试该方法并且对钩子无忧无虑。

任何解决方案...

编辑

我要进行单元测试的域中的示例代码:

class TestDomain{
   String activationDate
   def beforeInsert() {
      this.activationDate = (this.activationDate) ?: new Date()//first login date would come here though
      encodePassword()
   }
}

如何在 beforeInsert 之前进行单元测试,否则我最终会编写集成测试用例?

也许像这样的单元测试:

import grails.test.mixin.TestFor

@TestFor(TestDomain)
class TestDomainSpec extends Specification {
    def "test beforeSave"() {
        given:
            mockForConstraintsTests(TestDomain)
        when:
            def testDomain = new TestDomain().save(flush:true)
        then:
            testDomain.activationDate != null
    }
}