[英]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.