上面看到,每个属性只有一种核查规则,但是如果我们要在不同的场景中使用不同的规则,那么这个时候应该怎么办呢,分组就来了,新增一个注解Matchers
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Matchers {
Matcher[] value();
}
使用时候,通过属性中的group进行定义不同的规则,核查的时候,采用函数MkValidators.check(String group, Object obj)
进行核查,如果采用MkValidators.check(Object obj)
则采用默认的组,即下面的没有设置组的匹配规则
@Data
@Accessors(chain = true)
public class GroupEntity {
@Matchers({
@Matcher(range = "[50, 100]", accept = false),
@Matcher(group = "test1", range = "[12, 23]", accept = false),
@Matcher(group = "test2", range = "[1, 10]", accept = false)
})
private Integer age;
@Matchers({
@Matcher(value = {"beijing", "shanghai", "guangzhou"}),
@Matcher(group = "test1", value = {"beijing", "shanghai"}),
@Matcher(group = "test2", value = {"shanghai", "hangzhou"})
})
private String name;
}
用例
def "测试指定分组"() {
given:
GroupEntity entity = new GroupEntity().setAge(age).setName(name)
expect:
def act = MkValidators.check("test1", entity);
Assert.assertEquals(result, act)
if (!act) {
println MkValidators.errMsg
}
where:
age | name | result
10 | "shanghai" | true
12 | "beijing" | false
23 | "beijing" | false
50 | "beijing" | true
100 | "guangzhou" | false
}