【问题标题】:grails domain-class validator troubles testinggrails 域类验证器测试麻烦
【发布时间】:2018-11-15 10:48:08
【问题描述】:

我在域类中有一个验证器,但我在测试 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

有什么想法吗?

【问题讨论】:

    标签: unit-testing grails spock


    【解决方案1】:

    找到了解决方案,我还得模拟 Lagertyp,像这样:

    @Mock([Lagerort,Lagertyp])
    

    似乎我必须在@Mock 列表中包含作为测试一部分的所有域类,即使是间接引用的那些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多