1 package org.junit.validator; 2 3 import org.junit.Rule; 4 import org.junit.Test; 5 import org.junit.rules.ExpectedException; 6 7 import java.lang.annotation.Annotation; 8 9 import static org.hamcrest.core.Is.is; 10 import static org.hamcrest.core.IsInstanceOf.instanceOf; 11 import static org.junit.Assert.assertThat; 12 13 public class AnnotationValidatorFactoryTest { 14 15 @Rule 16 public ExpectedException exception = ExpectedException.none(); 17 18 @Test 19 public void createAnnotationValidator() { 20 ValidateWith validateWith = SampleTestWithValidator.class.getAnnotation(ValidateWith.class); 21 AnnotationValidator annotationValidator = new AnnotationValidatorFactory().createAnnotationValidator(validateWith); 22 assertThat(annotationValidator, is(instanceOf(Validator.class))); 23 } 24 25 @Test 26 public void exceptionWhenAnnotationWithNullClassIsPassedIn() { 27 exception.expect(IllegalArgumentException.class); 28 exception.expectMessage("Can't create validator, value is null in " + 29 "annotation org.junit.validator.AnnotationValidatorFactoryTest$ValidatorWithNullValue"); 30 31 new AnnotationValidatorFactory().createAnnotationValidator(new ValidatorWithNullValue()); 32 } 33 34 35 public static class ValidatorWithNullValue implements ValidateWith { 36 public Class<? extends AnnotationValidator> value() { 37 return null; 38 } 39 40 public Class<? extends Annotation> annotationType() { 41 return ValidateWith.class; 42 } 43 } 44 45 @ValidateWith(value = Validator.class) 46 public static class SampleTestWithValidator { 47 } 48 49 public static class Validator extends AnnotationValidator { 50 } 51 52 @Test 53 public void exceptionWhenAnnotationValidatorCantBeCreated() { 54 ValidateWith validateWith = SampleTestWithValidatorThatThrowsException.class.getAnnotation(ValidateWith.class); 55 exception.expect(RuntimeException.class); 56 exception.expectMessage("Exception received when creating AnnotationValidator class " + 57 "org.junit.validator.AnnotationValidatorFactoryTest$ValidatorThatThrowsException"); 58 new AnnotationValidatorFactory().createAnnotationValidator(validateWith); 59 } 60 61 @ValidateWith(value = ValidatorThatThrowsException.class) 62 public static class SampleTestWithValidatorThatThrowsException { 63 } 64 65 public static class ValidatorThatThrowsException extends AnnotationValidator { 66 public ValidatorThatThrowsException() throws InstantiationException { 67 throw new InstantiationException("Simulating exception in test"); 68 } 69 } 70 }