1
2
3
4
5
6 package mockit.internal.reflection;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9 import static org.junit.jupiter.api.Assertions.assertNull;
10 import static org.junit.jupiter.api.Assertions.assertThrows;
11
12 import java.lang.annotation.Retention;
13 import java.lang.annotation.RetentionPolicy;
14
15 import org.junit.jupiter.api.Test;
16
17 final class AnnotationReflectionTest {
18
19 @Retention(RetentionPolicy.RUNTIME)
20 @interface SampleAnnotation {
21 String value() default "test";
22
23 String name() default "sample";
24 }
25
26 @SampleAnnotation("hello")
27 static void annotatedMethod() {
28 }
29
30 @Test
31 void readAnnotationAttributeReturnsValue() throws NoSuchMethodException {
32 SampleAnnotation annotation = AnnotationReflectionTest.class.getDeclaredMethod("annotatedMethod")
33 .getAnnotation(SampleAnnotation.class);
34 String value = AnnotationReflection.readAnnotationAttribute(annotation, "value");
35 assertEquals("hello", value);
36 }
37
38 @Test
39 void readAnnotationAttributeThrowsForMissingAttribute() throws NoSuchMethodException {
40 SampleAnnotation annotation = AnnotationReflectionTest.class.getDeclaredMethod("annotatedMethod")
41 .getAnnotation(SampleAnnotation.class);
42 assertThrows(RuntimeException.class,
43 () -> AnnotationReflection.readAnnotationAttribute(annotation, "nonExistent"));
44 }
45
46 @Test
47 void readAnnotationAttributeIfAvailableReturnsValue() throws NoSuchMethodException {
48 SampleAnnotation annotation = AnnotationReflectionTest.class.getDeclaredMethod("annotatedMethod")
49 .getAnnotation(SampleAnnotation.class);
50 String value = AnnotationReflection.readAnnotationAttributeIfAvailable(annotation, "value");
51 assertEquals("hello", value);
52 }
53
54 @Test
55 void readAnnotationAttributeIfAvailableReturnsNullForMissingAttribute() throws NoSuchMethodException {
56 SampleAnnotation annotation = AnnotationReflectionTest.class.getDeclaredMethod("annotatedMethod")
57 .getAnnotation(SampleAnnotation.class);
58 String value = AnnotationReflection.readAnnotationAttributeIfAvailable(annotation, "nonExistent");
59 assertNull(value);
60 }
61
62 @Test
63 void readAnnotationAttributeDefaultValue() throws NoSuchMethodException {
64 SampleAnnotation annotation = AnnotationReflectionTest.class.getDeclaredMethod("annotatedMethod")
65 .getAnnotation(SampleAnnotation.class);
66 String name = AnnotationReflection.readAnnotationAttribute(annotation, "name");
67 assertEquals("sample", name);
68 }
69 }