/************************************************
 * Copyright (c) Shen Li. All rights reserved.  *
 * http://joyaop.sourceforge.net                *
 * -------------------------------------------- *
 * Distributable under LGPL license.            *
 * See terms of license at gnu.org.             *
 ************************************************/
package net.sf.joyaop.extension.mock;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author Shen Li
 */
public abstract class AbstractClassMock {
    public static Object mock(Class clazz) {
        return mock(clazz, new Class[0], new Object[0]);
    }

    public static Object mock(Class clazz, Class[] argTypes, Object[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new CallbackImpl());
        return enhancer.create(argTypes, args);
    }

    private static class CallbackImpl implements MethodInterceptor {
        public Object intercept(Object proxy, Method method,
                                Object[] args, MethodProxy methodProxy) throws Throwable {
            if (Modifier.isAbstract(method.getModifiers())) {
                throw new UnsupportedOperationException();
            }
            return methodProxy.invokeSuper(proxy, args);
        }
    }
}
