Вопрос

I have this object

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

    static constraints = {
        items minSize: 1
    }
}

but this test fail:

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

    assert !foo.validate()
}

What do I do wrong? It's supposed to work according to grails 'minSize' documentation: "Sets the minimum size of a collection or number property."

Это было полезно?

Решение

The documentation might be misleading. The minSize constraint will only apply to:

  1. String
  2. Arrays
  3. Classes which implements the java.util.Collection interface

java.util.Map however does not extend the java.util.Collection interface

See the supports method of MinSizeConstraint:

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

You can develop your own custom constraint for this or a custom validator as suggested by Thermech

In addition, in order for Grails to mock the validate method properly your test class should be something like:

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

        foo.items = [:]

        assert !foo.validate()
    } }

Другие советы

The only way I found, is with a custom validator:

static constraints = {
    items validator:  { Map map, obj, errors ->
        if (map.size() < 1) errors.rejectValue('items', 'minSize.notmet')
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top