简体   繁体   中英

How can I test validation annotations?

How can I test annotation based validation? I know that it only works with things that know how to recognize the annotations, and it seems that by default the test frameworks (JUnit, TestNG) do not recognize these.

public class Foo {

    @NotNull
    @Size(min = 2, max = 110)
    private String description;

    public method describe ( String desc ) {
       this.description = desc;
    }
}

update : For example how would I go about ensuring that when I attempt to set the description, that it will throw an error (if used by things that recognize the annotations) if I do Foo.new.describe( ' ' ) or Foo.new.describe( null ) .

Your question is kinda confusing. I'll try to answer two different aspects of the question.

How can I test validation annotations?

If those validation Annotations conforms to Java JSR-303 Bean Validation (which seems to be this case), you can validate those objects and make the desired assertions on Unit Tests using Hibernate Validator or another implementation.

Example:

public class FooTest {

   private static Validator validator;

   @BeforeClass
   public static void setUp() {
      ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      validator = factory.getValidator();
   }

   @Test
   public void checkIfIsNull() {
      Foo foo = new Foo(); // Field is null at this point

      Set<ConstraintViolation<Car>> constraintViolations = validator.validate(foo);

      assertTrue(constraintViolations.size() > 0);
   }
}

--

For example how would I go about ensuring that when I attempt to set the description, that it will throw an error (if used by things that recognize the annotations) if I do Foo.new.describe(' ') or Foo.new.describe(null)

You're talking about runtime validation here, not Unit Testing. You can check and throw the recommended exception this way:

public void describe(String desc) {
    if (desc == null || desc.trim().isEmpty())
        throw new IllegalArgumentException("[desc] parameter is null or empty");

    ...
}

PS: Here I'm assuming that the describe(String) method is not actually setDescription(String) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM