001/*
002 * (C) Copyright 2013 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 *
016 * Contributors:
017 *     dmetzler
018 */
019package org.nuxeo.runtime.mockito;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.nuxeo.runtime.api.DefaultServiceProvider;
025import org.nuxeo.runtime.api.Framework;
026import org.nuxeo.runtime.api.ServiceProvider;
027
028/**
029 * @since 5.7.8
030 */
031public class MockProvider implements ServiceProvider {
032
033    protected ServiceProvider next;
034
035    protected final Map<Class<?>, Object> mocks = new HashMap<>();
036
037    public MockProvider() {
038    }
039
040    public void bind(Class<?> klass, Object mock) {
041        mocks.put(klass, mock);
042    }
043
044    public void clearBindings() {
045        mocks.clear();
046    }
047
048    public void installSelf() {
049        next = DefaultServiceProvider.getProvider();
050        DefaultServiceProvider.setProvider(this);
051    }
052
053    public void uninstallSelf() {
054        DefaultServiceProvider.setProvider(next);
055        next = null;
056    }
057
058    @Override
059    public <T> T getService(Class<T> serviceClass) {
060        if (mocks.containsKey(serviceClass)) {
061            return serviceClass.cast(mocks.get(serviceClass));
062        }
063        if (next != null) {
064            return next.getService(serviceClass);
065        }
066        return Framework.getRuntime().getService(serviceClass);
067    }
068
069}