unit-testing - Grails 域验证器 : Two fields, 可以为 null,但不能同时为 null

标签 unit-testing validation grails

我有一个域,其中有两个字段可以为空,但不能同时为空。所以像这样

class Character {
    Association association
    String otherAssociation
    static constraints = {
        association (validator: {val, obj->  if (!val && !obj.otherAssociation) return 'league.association.mustbeone'})
        otherAssociation (validator: {val, obj->  if (!val && !obj.association) return 'league.association.mustbeone'})
    }
}

但是当我运行如下测试时,我只会失败

void testCreateWithAssociation() {
   def assoc = new Association(name:'Fake Association').save()
   def assoccha = new Character(association:assoc).save()

   assert assoccha
}
void testCreateWithoutAssociation() {
    def cha = new Character(otherAssociation:'Fake Association').save()
    assert cha
}

我做错了什么?

编辑 看起来如果我将代码分解成这样的东西:

def assoc = new Association(name:'Fake Association')
assoc.save()

一切正常。但现在我想知道为什么我不能像在其他测试中那样将 .save() 放在同一行中并且它可以工作。

最佳答案

为了使您的测试通过,您的字段关联和 otherAssociation 必须为空。为两者添加可空约束,如下所示:

static constraints = {
    association nullable: true, validator: {val, obj->  if (!val && !obj.otherAssociation) return 'league.association.mustbeone'}
    otherAssociation nullable: true, validator: {val, obj->  if (!val && !obj.association) return 'league.association.mustbeone'}
}

我试过了,有效

关于unit-testing - Grails 域验证器 : Two fields, 可以为 null,但不能同时为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16455341/

相关文章:

Javascript - 单元测试中的模拟 FormData.entries()

c# - 如何在 Visual Studio 2010 中执行单元测试之前不构建

node.js - 如何在 DTO nestJs 上设置默认值?

validation - HAproxy+Lua : Return requests if validation fails from Lua script

grails - 初学Groovy

grails - 为Apache Camel 设置跟踪

javascript - karma Jasmine 没有执行所有测试

regex - grails 2.5如何使用验证器内的服务验证域对象密码

grails - 将 Controller 名称映射到url(带有包)

javascript - Jest 期望使用不包含特定字段的对象调用 mock