Mock objects with Java Proxy


public class MockUtils {
    /**
     * Simple mocking without any bells & whistles.
     *
     * @see WrappingProxy
     */
    @SuppressWarnings("unchecked")
    public static  U mock(Class u, Object withMethods) {
        return (U) Proxy.newProxyInstance(u.getClassLoader(), new Class[] { u }, new WrappingProxy(withMethods));
    }

    /**
     * Init with the object which has the methods that are to be invoked.
     */
    public static class WrappingProxy implements InvocationHandler {

        private Object o = null;

        public WrappingProxy(Object o) {
            super();
            this.o = o;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            try {
                // hashCode may also be needed if used in map
                if (methodName.equals("equals") && args.length == 1 && method.getReturnType() == boolean.class) {
                    return o.equals(args[0]);
                }
                Class[] parameterTypes = new Class[args == null ? 0 : args.length];
                Method m = o.getClass().getMethod(methodName, parameterTypes);
                m.setAccessible(true);
                return m.invoke(o, args);
            } catch (NoSuchMethodException e) {
                return null;
            } catch (InvocationTargetException e) {
                throw e.getTargetException();
            } catch (Throwable e) {
                throw e;
            }
        }
    }
}

public class MyClass {}

MyClass myO = MockUtils.mock(MyClass.class, new Object() {
        public String getName() {
            return "this is my name";
        }
    });