Grails 域验证器:两个字段,其中一个可以为空,但不能同时为空

How*_*wes 2 validation grails unit-testing

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

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'})
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑 看起来如果我将代码分解为如下所示:

def assoc = new Association(name:'Fake Association')
assoc.save()
Run Code Online (Sandbox Code Playgroud)

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

The*_*ech 5

为了使您的测试通过,您的字段关联和 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'}
}
Run Code Online (Sandbox Code Playgroud)

我尝试过并且有效