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