001/*******************************************************************************
002 * (C) Copyright 2014 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.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 *******************************************************************************/
014package org.nuxeo.runtime.mockito;
015
016import static org.mockito.MockitoAnnotations.initMocks;
017
018import java.lang.reflect.Field;
019
020import org.mockito.configuration.IMockitoConfiguration;
021import org.mockito.internal.configuration.GlobalConfiguration;
022import org.nuxeo.runtime.api.DefaultServiceProvider;
023import org.nuxeo.runtime.test.protocols.inline.InlineURLFactory;
024import org.nuxeo.runtime.test.runner.FeaturesRunner;
025import org.nuxeo.runtime.test.runner.SimpleFeature;
026
027public class MockitoFeature extends SimpleFeature {
028
029    protected final MockProvider provider = new MockProvider();
030
031    @Override
032    public void start(FeaturesRunner runner) throws Exception {
033        InlineURLFactory.install();
034        provider.installSelf();
035    }
036
037    @Override
038    public void testCreated(Object test) throws Exception {
039        DefaultServiceProvider.setProvider(provider);
040        initMocks(test);
041    }
042
043    @Override
044    public void afterRun(FeaturesRunner runner) throws Exception {
045        cleanupThread();
046    }
047
048    @Override
049    public void stop(FeaturesRunner runner) throws Exception {
050        InlineURLFactory.uninstall();
051        provider.uninstallSelf();
052    }
053
054    protected void cleanupThread() throws NoSuchFieldException, SecurityException, IllegalArgumentException,
055            IllegalAccessException {
056        Field f = GlobalConfiguration.class.getDeclaredField("globalConfiguration");
057        f.setAccessible(true);
058        ThreadLocal<IMockitoConfiguration> holder = (ThreadLocal<IMockitoConfiguration>) f.get(null);
059        holder.remove();
060    }
061}