001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     dmetzler
016 */
017package org.nuxeo.runtime.mockito;
018
019import org.mockito.configuration.AnnotationEngine;
020import org.mockito.internal.configuration.InjectingAnnotationEngine;
021import org.mockito.internal.configuration.SpyAnnotationEngine;
022
023/**
024 * @since 5.7.8
025 */
026public class NuxeoInjectingAnnotationEngine extends InjectingAnnotationEngine {
027    private AnnotationEngine delegate = new NuxeoDefaultAnnotationEngine();
028
029    private AnnotationEngine spyAnnotationEngine = new SpyAnnotationEngine();
030
031    /**
032     * Process the fields of the test instance and create Mocks, Spies, Captors and inject them on fields annotated
033     * @InjectMocks.
034     * <p>
035     * This code process the test class and the super classes.
036     * <ol>
037     * <li>First create Mocks, Spies, Captors.</li>
038     * <li>Then try to inject them.</li>
039     * </ol>
040     *
041     * @param clazz Not used
042     * @param testInstance The instance of the test, should not be null.
043     * @see org.mockito.configuration.AnnotationEngine#process(Class, Object)
044     */
045    @Override
046    public void process(Class<?> clazz, Object testInstance) {
047        processIndependentAnnotations(testInstance.getClass(), testInstance);
048        processInjectMocks(testInstance.getClass(), testInstance);
049    }
050
051    private void processInjectMocks(final Class<?> clazz, final Object testInstance) {
052        Class<?> classContext = clazz;
053        while (classContext != Object.class) {
054            injectMocks(testInstance);
055            classContext = classContext.getSuperclass();
056        }
057    }
058
059    private void processIndependentAnnotations(final Class<?> clazz, final Object testInstance) {
060        Class<?> classContext = clazz;
061        while (classContext != Object.class) {
062            // this will create @Mocks, @Captors, etc:
063            delegate.process(classContext, testInstance);
064            // this will create @Spies:
065            spyAnnotationEngine.process(classContext, testInstance);
066
067            classContext = classContext.getSuperclass();
068        }
069    }
070
071}