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 org.apache.commons.lang3.reflect.FieldUtils; 021import org.mockito.configuration.IMockitoConfiguration; 022import org.mockito.internal.configuration.GlobalConfiguration; 023import org.nuxeo.runtime.api.DefaultServiceProvider; 024import org.nuxeo.runtime.test.runner.FeaturesRunner; 025import org.nuxeo.runtime.test.runner.RunnerFeature; 026 027public class MockitoFeature implements RunnerFeature { 028 029 protected final MockProvider provider = new MockProvider(); 030 031 @Override 032 public void start(FeaturesRunner runner) { 033 provider.installSelf(); 034 } 035 036 @Override 037 public void testCreated(Object test) { 038 DefaultServiceProvider.setProvider(provider); 039 initMocks(test); 040 } 041 042 @Override 043 public void afterRun(FeaturesRunner runner) throws Exception { 044 cleanupThread(); 045 } 046 047 @Override 048 public void stop(FeaturesRunner runner) { 049 provider.uninstallSelf(); 050 } 051 052 protected void cleanupThread() throws ReflectiveOperationException { 053 ThreadLocal<IMockitoConfiguration> holder = (ThreadLocal<IMockitoConfiguration>) FieldUtils.readStaticField(GlobalConfiguration.class, "globalConfiguration", true); 054 holder.remove(); 055 } 056}