1 package mockit;
2
3 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4 import static org.junit.jupiter.api.Assertions.assertEquals;
5 import static org.junit.jupiter.api.Assertions.assertFalse;
6 import static org.junit.jupiter.api.Assertions.assertNull;
7 import static org.junit.jupiter.api.Assertions.assertSame;
8
9 import edu.umd.cs.findbugs.annotations.NonNull;
10
11 import java.lang.annotation.Annotation;
12
13 import javax.annotation.Resource;
14
15 import org.checkerframework.checker.index.qual.NonNegative;
16 import org.junit.jupiter.api.Test;
17
18
19
20
21 final class MockedAnnotationsTest {
22
23
24
25
26 public @interface MyAnnotation {
27
28
29
30
31
32
33 String value();
34
35
36
37
38
39
40 boolean flag() default true;
41
42
43
44
45
46
47 String[] values() default {};
48 }
49
50
51
52
53
54
55
56 @Test
57 void specifyValuesForAnnotationAttributes(@Mocked final MyAnnotation a) {
58 assertSame(MyAnnotation.class, a.annotationType());
59
60 new Expectations() {
61 {
62 a.flag();
63 result = false;
64 a.value();
65 result = "test";
66 a.values();
67 returns("abc", "dEf");
68 }
69 };
70
71 assertFalse(a.flag());
72 assertEquals("test", a.value());
73 assertArrayEquals(new String[] { "abc", "dEf" }, a.values());
74 }
75
76
77
78
79
80
81
82 @Test
83 void verifyUsesOfAnnotationAttributes(@Mocked final MyAnnotation a) {
84 new Expectations() {
85 {
86 a.value();
87 result = "test";
88 times = 2;
89 a.values();
90 returns("abc", "dEf");
91 }
92 };
93
94
95
96 assertFalse(a.flag());
97
98 assertEquals("test", a.value());
99 assertArrayEquals(new String[] { "abc", "dEf" }, a.values());
100 a.value();
101
102 new FullVerifications() {
103 {
104
105 a.flag();
106 }
107 };
108 }
109
110
111
112
113 @Resource
114 public interface AnInterface {
115 }
116
117
118
119
120
121
122
123 @Test
124 void mockingAnAnnotatedPublicInterface(@Mocked AnInterface mock) {
125 Annotation[] mockClassAnnotations = mock.getClass().getAnnotations();
126
127 assertEquals(0, mockClassAnnotations.length);
128 }
129
130
131
132
133 static class ClassWithNullabilityAnnotations {
134
135
136
137
138
139
140
141
142
143
144
145 @NonNull
146 String doSomething(@NonNegative int i, @NonNull Object obj) {
147 return "";
148 }
149 }
150
151
152
153
154
155
156
157 @Test
158 void mockClassWithNullabilityAnnotations(@Injectable final ClassWithNullabilityAnnotations mock) {
159 new Expectations() {
160 {
161 mock.doSomething(anyInt, any);
162 result = "test";
163 }
164 };
165
166 assertEquals("test", mock.doSomething(123, "test"));
167 }
168
169
170
171
172 static final class ClassWithAnnotatedField {
173
174 @Resource(type = int.class)
175 Object aField;
176 }
177
178
179
180
181
182
183
184 @Test
185 void mockClassHavingFieldAnnotatedWithAttributeHavingAPrimitiveClassAsValue(@Mocked ClassWithAnnotatedField mock) {
186 assertNull(mock.aField);
187 }
188 }