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.runner.FeaturesRunner; 026import org.nuxeo.runtime.test.runner.RunnerFeature; 027 028public class MockitoFeature implements RunnerFeature { 029 030 protected final MockProvider provider = new MockProvider(); 031 032 @Override 033 public void start(FeaturesRunner runner) { 034 provider.installSelf(); 035 } 036 037 @Override 038 public void testCreated(Object test) { 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) { 050 provider.uninstallSelf(); 051 } 052 053 protected void cleanupThread() throws NoSuchFieldException, SecurityException, IllegalArgumentException, 054 IllegalAccessException { 055 Field f = GlobalConfiguration.class.getDeclaredField("globalConfiguration"); 056 f.setAccessible(true); 057 ThreadLocal<IMockitoConfiguration> holder = (ThreadLocal<IMockitoConfiguration>) f.get(null); 058 holder.remove(); 059 } 060}