我有一个域,其中有两个字段可以为空,但不能同时为空。所以像这样
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/