-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
SpyAnnotationEngine.java
170 lines (158 loc) · 6.98 KB
/
SpyAnnotationEngine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.configuration;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.withSettings;
import static org.mockito.internal.exceptions.Reporter.unsupportedCombinationOfAnnotations;
import static org.mockito.internal.util.StringUtil.join;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockSettings;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.util.MockUtil;
import org.mockito.plugins.AnnotationEngine;
import org.mockito.plugins.MemberAccessor;
/**
* Process fields annotated with @Spy.
* <p/>
* <p>
* Will try transform the field in a spy as with <code>Mockito.spy()</code>.
* </p>
* <p/>
* <p>
* If the field is not initialized, will try to initialize it, with a no-arg constructor.
* </p>
* <p/>
* <p>
* If the field is also annotated with the <strong>compatible</strong> @InjectMocks then the field will be ignored,
* The injection engine will handle this specific case.
* </p>
* <p/>
* <p>This engine will fail, if the field is also annotated with incompatible Mockito annotations.
*/
@SuppressWarnings({"unchecked"})
public class SpyAnnotationEngine
implements AnnotationEngine, org.mockito.configuration.AnnotationEngine {
@Override
public AutoCloseable process(Class<?> context, Object testInstance) {
Field[] fields = context.getDeclaredFields();
MemberAccessor accessor = Plugins.getMemberAccessor();
for (Field field : fields) {
if (field.isAnnotationPresent(Spy.class)
&& !field.isAnnotationPresent(InjectMocks.class)) {
assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class);
Object instance;
try {
instance = accessor.get(field, testInstance);
if (MockUtil.isMock(instance)) {
// instance has been spied earlier
// for example happens when MockitoAnnotations.openMocks is called two
// times.
Mockito.reset(instance);
} else if (instance != null) {
accessor.set(field, testInstance, spyInstance(field, instance));
} else {
accessor.set(field, testInstance, spyNewInstance(testInstance, field));
}
} catch (Exception e) {
throw new MockitoException(
"Unable to initialize @Spy annotated field '"
+ field.getName()
+ "'.\n"
+ e.getMessage(),
e);
}
}
}
return new NoAction();
}
private static Object spyInstance(Field field, Object instance) {
return Mockito.mock(
instance.getClass(),
withSettings()
.spiedInstance(instance)
.defaultAnswer(CALLS_REAL_METHODS)
.name(field.getName()));
}
private static Object spyNewInstance(Object testInstance, Field field)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
MockSettings settings =
withSettings().defaultAnswer(CALLS_REAL_METHODS).name(field.getName());
Class<?> type = field.getType();
if (type.isInterface()) {
return Mockito.mock(type, settings.useConstructor());
}
int modifiers = type.getModifiers();
if (typeIsPrivateAbstractInnerClass(type, modifiers)) {
throw new MockitoException(
join(
"@Spy annotation can't initialize private abstract inner classes.",
" inner class: '" + type.getSimpleName() + "'",
" outer class: '" + type.getEnclosingClass().getSimpleName() + "'",
"",
"You should augment the visibility of this inner class"));
}
if (typeIsNonStaticInnerClass(type, modifiers)) {
Class<?> enclosing = type.getEnclosingClass();
if (!enclosing.isInstance(testInstance)) {
throw new MockitoException(
join(
"@Spy annotation can only initialize inner classes declared in the test.",
" inner class: '" + type.getSimpleName() + "'",
" outer class: '" + enclosing.getSimpleName() + "'",
""));
}
return Mockito.mock(type, settings.useConstructor().outerInstance(testInstance));
}
Constructor<?> constructor = noArgConstructorOf(type);
if (Modifier.isPrivate(constructor.getModifiers())) {
MemberAccessor accessor = Plugins.getMemberAccessor();
return Mockito.mock(type, settings.spiedInstance(accessor.newInstance(constructor)));
} else {
return Mockito.mock(type, settings.useConstructor());
}
}
private static Constructor<?> noArgConstructorOf(Class<?> type) {
Constructor<?> constructor;
try {
constructor = type.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
throw new MockitoException(
"Please ensure that the type '"
+ type.getSimpleName()
+ "' has a no-arg constructor.");
}
return constructor;
}
private static boolean typeIsNonStaticInnerClass(Class<?> type, int modifiers) {
return !Modifier.isStatic(modifiers) && type.getEnclosingClass() != null;
}
private static boolean typeIsPrivateAbstractInnerClass(Class<?> type, int modifiers) {
return Modifier.isPrivate(modifiers)
&& Modifier.isAbstract(modifiers)
&& type.getEnclosingClass() != null;
}
// TODO duplicated elsewhere
private static void assertNoIncompatibleAnnotations(
Class<? extends Annotation> annotation,
Field field,
Class<? extends Annotation>... undesiredAnnotations) {
for (Class<? extends Annotation> u : undesiredAnnotations) {
if (field.isAnnotationPresent(u)) {
throw unsupportedCombinationOfAnnotations(
annotation.getSimpleName(), u.getSimpleName());
}
}
}
}