org.mockito.internal.configuration.InjectingAnnotationEngine Maven / Gradle / Ivy
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.configuration;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.configuration.AnnotationEngine;
import org.mockito.exceptions.Reporter;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.reflection.FieldReader;
/**
* See {@link MockitoAnnotations}
*/
@SuppressWarnings({"deprecation", "unchecked"})
public class InjectingAnnotationEngine implements AnnotationEngine {
AnnotationEngine delegate = new DefaultAnnotationEngine();
AnnotationEngine spyAnnotationEngine = new SpyAnnotationEngine();
/* (non-Javadoc)
* @see org.mockito.AnnotationEngine#createMockFor(java.lang.annotation.Annotation, java.lang.reflect.Field)
*/
public Object createMockFor(Annotation annotation, Field field) {
return delegate.createMockFor(annotation, field);
}
public void process(Class> context, Object testClass) {
//this will create @Mocks, @Captors, etc:
delegate.process(context, testClass);
//this will create @Spies:
spyAnnotationEngine.process(context, testClass);
//this injects mocks
Field[] fields = context.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(InjectMocks.class)) {
assertNoAnnotations(field, Mock.class, org.mockito.MockitoAnnotations.Mock.class, Captor.class);
injectMocks(testClass);
}
}
}
void assertNoAnnotations(Field field, Class ... annotations) {
for (Class annotation : annotations) {
if (field.isAnnotationPresent(annotation)) {
new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName());
}
}
}
/**
* Initializes mock/spies dependencies for objects annotated with
* @InjectMocks for given testClass.
*
* See examples in javadoc for {@link MockitoAnnotations} class.
*
* @param testClass
* Test class, usually this
*/
public void injectMocks(Object testClass) {
Class> clazz = testClass.getClass();
Set mockDependents = new HashSet();
Set
© 2015 - 2024 Weber Informatics LLC | Privacy Policy