![](/img/trans.png)
[英]Overriding event closure on Grails GORM domain class for unit testing
[英]Grails : Spock : Unit testing GORM domain class hooks
通常,我最终会通过为域编写测试用例来编写约束条件和任何自定义方法(由我们在应用程序中创建),因为我们知道我们不应该测试显而易见的方法。
但是,当我们开始使用coverage插件时,我们发现我们的域代码行并未完全覆盖,这是由于我们从未为其编写测试用例的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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.