001/* 002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.nuxeo.runtime.mockito; 017 018import static org.mockito.MockitoAnnotations.initMocks; 019 020import java.lang.reflect.Field; 021 022import org.mockito.configuration.IMockitoConfiguration; 023import org.mockito.internal.configuration.GlobalConfiguration; 024import org.nuxeo.runtime.api.DefaultServiceProvider; 025import org.nuxeo.runtime.test.protocols.inline.InlineURLFactory; 026import org.nuxeo.runtime.test.runner.FeaturesRunner; 027import org.nuxeo.runtime.test.runner.SimpleFeature; 028 029public class MockitoFeature extends SimpleFeature { 030 031 protected final MockProvider provider = new MockProvider(); 032 033 @Override 034 public void start(FeaturesRunner runner) throws Exception { 035 InlineURLFactory.install(); 036 provider.installSelf(); 037 } 038 039 @Override 040 public void testCreated(Object test) throws Exception { 041 DefaultServiceProvider.setProvider(provider); 042 initMocks(test); 043 } 044 045 @Override 046 public void afterRun(FeaturesRunner runner) throws Exception { 047 cleanupThread(); 048 } 049 050 @Override 051 public void stop(FeaturesRunner runner) throws Exception { 052 InlineURLFactory.uninstall(); 053 provider.uninstallSelf(); 054 } 055 056 protected void cleanupThread() throws NoSuchFieldException, SecurityException, IllegalArgumentException, 057 IllegalAccessException { 058 Field f = GlobalConfiguration.class.getDeclaredField("globalConfiguration"); 059 f.setAccessible(true); 060 ThreadLocal<IMockitoConfiguration> holder = (ThreadLocal<IMockitoConfiguration>) f.get(null); 061 holder.remove(); 062 } 063}