提问者:小点点

圣杯:斯波克:单元测试GORM域类钩子


通常,我会为一个域编写测试用例,为约束和任何自定义方法(由我们在应用程序中创建)编写测试用例。

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

有没有办法测试这些。一种看起来很明显但不合适的方法是在这些钩子中调用另一个方法(包含之前在钩子中的所有代码),并只测试该方法,而不用担心钩子。

有解决办法吗...

编辑

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

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

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


共1个答案

匿名用户

也许是这样的单元测试:

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
    }
}