Skip to content

Commit 625614a

Browse files
committed
Stop "collecting" annotations in MockitoAnnotationDetector
There is no need to collect/track the actual annotations. Rather, we only need to know if there is at least once such annotation present.
1 parent 40ca83d commit 625614a

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoTestExecutionListener.java

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
import java.lang.annotation.Annotation;
2020
import java.lang.reflect.AnnotatedElement;
2121
import java.util.Arrays;
22-
import java.util.HashSet;
23-
import java.util.Set;
22+
import java.util.concurrent.atomic.AtomicBoolean;
2423
import java.util.function.Predicate;
2524

2625
import org.mockito.Mockito;
@@ -146,16 +145,23 @@ private static class MockitoAnnotationDetector {
146145
};
147146

148147
static boolean hasMockitoAnnotations(Class<?> testClass) {
149-
Set<Annotation> annotations = new HashSet<>();
150-
collect(testClass, annotations);
151-
ReflectionUtils.doWithFields(testClass, field -> collect(field, annotations));
152-
return !annotations.isEmpty();
148+
if (isAnnotated(testClass)) {
149+
return true;
150+
}
151+
// TODO Ideally we should short-circuit the search once we've found a Mockito annotation,
152+
// since there's no need to continue searching additional fields or further up the class
153+
// hierarchy; however, that is not possible with ReflectionUtils#doWithFields. Plus, the
154+
// previous invocation of isAnnotated(testClass) only finds annotations declared directly
155+
// on the test class. So, we'll likely need a completely different approach that combines
156+
// the "test class/interface is annotated?" and "field is annotated?" checks in a single
157+
// search algorithm.
158+
AtomicBoolean found = new AtomicBoolean();
159+
ReflectionUtils.doWithFields(testClass, field -> found.set(true), MockitoAnnotationDetector::isAnnotated);
160+
return found.get();
153161
}
154162

155-
static void collect(AnnotatedElement annotatedElement, Set<Annotation> annotations) {
156-
Arrays.stream(annotatedElement.getAnnotations())
157-
.filter(isMockitoAnnotation)
158-
.forEach(annotations::add);
163+
private static boolean isAnnotated(AnnotatedElement annotatedElement) {
164+
return Arrays.stream(annotatedElement.getAnnotations()).anyMatch(isMockitoAnnotation);
159165
}
160166
}
161167

0 commit comments

Comments
 (0)