Grails域类验证器使测试麻烦

时间:2018-11-15 10:48:09

标签: unit-testing grails spock

我在域类中有一个验证器,并且在为Lagerort测试控制器时遇到问题。

com.example.xyz.LagerortControllerSpec > Test the update action performs an update on a valid domain instance FAILED
java.lang.IllegalStateException: Either class [com.example.xyz.Lagertyp] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.

如果我省略了验证器,那么一切都可以正常测试,但这不是我想要的。

域类:

 class Lagerort {

     String lagerort
     Lagertyp lagertyp
     String beschreibung

     static auditable = true

     static constraints = {
         lagerort(nullable: false, blank: false, unique: true)
         lagertyp(nullable: false, blank: false, validator: { val, obj ->
             // Only ONE Lagerort may be "Schrott"
             if (Lagertyp.count() > 0) {
                 def _LAGERTYPSTRING="Schrott"
                 Lagertyp lagertypschrott = Lagertyp.findByLagertyp(_LAGERTYPSTRING)
                 if (obj.lagertyp == lagertypschrott && Lagerort.countByLagertyp(lagertypschrott)>0) return ['lagerortschrottunique',_LAGERTYPSTRING]
             }
         })
         beschreibung(nullable: false, blank: false)

     }

     String toString(){lagerort}
 }

build.gradle中依赖项的testCompile部分如下所示:

testCompile "org.grails:grails-plugin-testing"
testCompile "org.grails.plugins:geb"
testCompile "org.grails.plugins:hibernate5"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"

我已经尝试在控制器测试的设置部分中创建一些Lagertyp类型的对象,以使Lagertyp.count() > 0对于验证者而言是正确的,但这也无济于事。

LagerortControllerSpec /测试的populateValidParams看起来像这样:

def populateValidParams(params) {
    assert params != null
    params["lagerort"] = 'Fa.Conrad'
    params["lagertyp"] = ["lagertyp": 'Fa.Conrad', "beschreibung": 'Motor befindet sich bei Fa.Conrad']
    params["beschreibung"] = 'in Reparatur bei Fa. Conrad'
}

LagerortController:https://pastebin.com/PpZ5zqMm

LagerortController的测试:https://pastebin.com/pxZ6UeVK

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

找到解决方案后,我还必须模拟Lagertyp,如下所示:

@Mock([Lagerort,Lagertyp])

似乎我必须将所有属于测试的一部分的域类包括在@Mock列表中,甚至包括那些间接引用的类。