1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.external;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23
24 import java.lang.annotation.Annotation;
25 import java.lang.annotation.Retention;
26 import java.lang.annotation.RetentionPolicy;
27 import java.lang.reflect.InvocationTargetException;
28
29 import org.apache.commons.lang3.AnnotationUtils;
30 import org.junit.jupiter.api.Test;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 public class AnnotationEqualsTest {
52 @Retention(RetentionPolicy.RUNTIME)
53 @interface Tag {
54 String value();
55 }
56
57 static class ThrowingTag implements Tag {
58 @Override
59 public Class<? extends Annotation> annotationType() {
60 return Tag.class;
61 }
62
63 @Override
64 public String value() {
65 throw new IllegalArgumentException("boom");
66 }
67 }
68
69 @Tag("value")
70 private final Object a = new Object();
71 @Tag("value")
72 private final Object b = new Object();
73
74 @Test
75 void equalsWorksOnPackagePrivateAnnotations() throws Exception {
76 final Tag tagA = getClass().getDeclaredField("a").getAnnotation(Tag.class);
77 final Tag tagB = getClass().getDeclaredField("b").getAnnotation(Tag.class);
78 assertTrue(AnnotationUtils.equals(tagA, tagB));
79 }
80
81 @Test
82 void equalsWrapsReflectiveOperationException() throws Exception {
83 final Tag tagA = new ThrowingTag();
84 final Tag tagB = getClass().getDeclaredField("b").getAnnotation(Tag.class);
85
86 final IllegalStateException ex =
87 assertThrows(IllegalStateException.class, () -> AnnotationUtils.equals(tagA, tagB));
88 assertInstanceOf(InvocationTargetException.class, ex.getCause());
89 assertEquals("boom", ((InvocationTargetException) ex.getCause()).getTargetException().getMessage());
90 }
91
92 @Test
93 void hashCodeWorksOnPackagePrivateAnnotations() throws Exception {
94 final Tag tag = getClass().getDeclaredField("a").getAnnotation(Tag.class);
95 assertEquals(tag.hashCode(), AnnotationUtils.hashCode(tag));
96 }
97
98 @Test
99 void toStringWorksOnPackagePrivateAnnotations() throws Exception {
100 final Tag tag = getClass().getDeclaredField("a").getAnnotation(Tag.class);
101 final String text = AnnotationUtils.toString(tag);
102 assertTrue(text.contains("value=value"), text);
103 }
104
105 }