All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mockito.internal.configuration.IndependentAnnotationEngine Maven / Gradle / Ivy

There is a newer version: 5.12.0
Show newest version
/*
 * 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.HashMap;
import java.util.Map;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.plugins.AnnotationEngine;

import static org.mockito.internal.exceptions.Reporter.moreThanOneAnnotationNotAllowed;
import static org.mockito.internal.util.reflection.FieldSetter.setField;

/**
 * Initializes fields annotated with @{@link org.mockito.Mock} or @{@link org.mockito.Captor}.
 *
 * 

* The {@link #process(Class, Object)} method implementation does not process super classes! * * @see MockitoAnnotations */ @SuppressWarnings("unchecked") public class IndependentAnnotationEngine implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { private final Map, FieldAnnotationProcessor> annotationProcessorMap = new HashMap, FieldAnnotationProcessor>(); public IndependentAnnotationEngine() { registerAnnotationProcessor(Mock.class, new MockAnnotationProcessor()); registerAnnotationProcessor(Captor.class, new CaptorAnnotationProcessor()); } private Object createMockFor(Annotation annotation, Field field) { return forAnnotation(annotation).process(annotation, field); } private FieldAnnotationProcessor forAnnotation(A annotation) { if (annotationProcessorMap.containsKey(annotation.annotationType())) { return (FieldAnnotationProcessor) annotationProcessorMap.get(annotation.annotationType()); } return new FieldAnnotationProcessor() { public Object process(A annotation, Field field) { return null; } }; } private void registerAnnotationProcessor(Class annotationClass, FieldAnnotationProcessor fieldAnnotationProcessor) { annotationProcessorMap.put(annotationClass, fieldAnnotationProcessor); } @Override public void process(Class clazz, Object testInstance) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { boolean alreadyAssigned = false; for(Annotation annotation : field.getAnnotations()) { Object mock = createMockFor(annotation, field); if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; try { setField(testInstance, field,mock); } catch (Exception e) { throw new MockitoException("Problems setting field " + field.getName() + " annotated with " + annotation, e); } } } } } void throwIfAlreadyAssigned(Field field, boolean alreadyAssigned) { if (alreadyAssigned) { throw moreThanOneAnnotationNotAllowed(field.getName()); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy