javax验证不再适用于方法-Javax错误?

时间:2018-06-22 10:03:34

标签: java validation

我很确定以前可以这样做,这是Javax验证程序中的错误吗?

我在下面的一个类(ValidClass)中使用@AssertTrue和@AssertFalse使用方法和字段注释进行验证。

当方法注释应该导致验证失败时,以下测试中的

2个失败(testFailB和testFailC)。

使用相同的注释,字段验证似乎可以正常工作(testFailA),该注释也被标记为也可以用于方法。

我是在做愚蠢的事情还是这是一个错误?

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;

import org.junit.Test;

public class ValidationsTest {
  private static final ValidatorFactory VALIDATION_FACTORY =
      Validation.buildDefaultValidatorFactory();

  public boolean isValid(Object object, Class<?>... groups) {
    Validator validator = VALIDATION_FACTORY.getValidator();
    Set<ConstraintViolation<Object>> violations = validator.validate(object, groups);
    return violations.isEmpty();
  }

  @Test
  public void testSuccess() {
    boolean a = true;
    boolean b = true;
    boolean c = true;
    assertTrue(isValid(new ValidClass(a, b, c), ValidGroup.class));
  }

  @Test
  public void testFailA() {
    boolean a = false;
    boolean b = true;
    boolean c = true;
    assertFalse(isValid(new ValidClass(a, b, c), ValidGroup.class));
  }

  @Test // THIS TEST FAILS
  public void testFailB() {
    boolean a = true;
    boolean b = false;
    boolean c = true;
    assertFalse(isValid(new ValidClass(a, b, c), ValidGroup.class));
  }

  @Test // THIS TEST FAILS
  public void testFailC() {
    boolean a = true;
    boolean b = true;
    boolean c = false;
    assertFalse(isValid(new ValidClass(a, b, c), ValidGroup.class));
  }

  public static class ValidClass {

    private boolean a;
    private boolean b;
    private boolean c;

    public ValidClass(boolean a, boolean b, boolean c) {
      this.a = a;
      this.b = b;
      this.c = c;
      this.thing = a;
    }

    @AssertTrue(message = "fail A", groups = ValidGroup.class)
    public boolean thing = a;

    @AssertTrue(message = "fail B", groups = ValidGroup.class)
    public boolean alwaysTrue() {
      return b;
    }

    @AssertFalse(message = "fail C", groups = ValidGroup.class)
    public boolean alwaysFalse() {
      return !c;
    }

  }

  public static interface ValidGroup {
  }

}

0 个答案:

没有答案