Create a gist now

Instantly share code, notes, and snippets.

@talios /Mocker.java Secret
Created Dec 12, 2011

package com.talios.xted;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Mocker implements InvocationHandler {
private Object wrapper;
private Mocker(Object wrapper) {
this.wrapper = wrapper;
}
public static <T> T mocker(Class<T> iface, Object wrapper) {
return (T) Proxy.newProxyInstance(wrapper.getClass().getClassLoader(),
new Class[] {iface}, new Mocker(wrapper));
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Method wrappedMethod = wrapper.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
return wrappedMethod.invoke(wrapper, objects);
}
}
package com.talios.xted;
public interface SomeInterface {
String name();
Integer age();
}
@Test
public void testApp() {
SomeInterface someInterface = Mocker.mocker(SomeInterface.class, new Object() {
String name() {
return "My Name is mock!";
}
});
System.out.println(someInterface.name());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment