【问题标题】:Grails: How to put a minSize constraints on mapGrails:如何在地图上放置 minSize 约束
【发布时间】:2013-03-26 22:52:08
【问题描述】:

我有这个东西

@Validateable
class Foo {
    Map<String, String> items

    static constraints = {
        items minSize: 1
    }
}

但是这个测试失败了:

@Test
void shouldNotValidateIfItemsIsEmpty() {
    Foo foo = new Foo(items: [:])

    assert !foo.validate()
}

我做错了什么?它应该根据 grails 'minSize' documentation 工作:“设置 collection 或 number 属性的最小大小。”

【问题讨论】:

  • 只是为了检查这是一个约束问题还是对象没有被验证:如果添加另一个不可为空的字段会发生什么?
  • 如果我将约束“nullable: true”添加到“items”并使用“items: null”进行相同的测试,验证失败并显示代码“nullable”
  • grails 在Map 属性和约束方面存在问题。见this issue

标签: validation grails map grails-2.2


【解决方案1】:

文档可能具有误导性。 minSize 约束仅适用于:

  1. 字符串
  2. 数组
  3. 实现 java.util.Collection 接口的类

java.util.Map 但是没有扩展java.util.Collection 接口

MinSizeConstraintsupports方法:

public boolean supports(Class type) {
        return type != null && (
                String.class.isAssignableFrom(type) ||
                Collection.class.isAssignableFrom(type) ||
                type.isArray());
    }

您可以为此开发自己的 custom constraint,或者按照 Thermech 的建议开发自定义验证器

此外,为了让 Grails 正确模拟 validate 方法,您的测试类应该是这样的:

@TestMixin(ControllerUnitTestMixin) class FooTest {
    @Test
    void shouldNotValidateIfItemsIsEmpty() {
        Foo foo = mockCommandObject Foo

        foo.items = [:]

        assert !foo.validate()
    } }

【讨论】:

    【解决方案2】:

    我发现的唯一方法是使用自定义验证器:

    static constraints = {
        items validator:  { Map map, obj, errors ->
            if (map.size() < 1) errors.rejectValue('items', 'minSize.notmet')
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多