-
-
Save talios/c887db3422b58d9c12b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.talios.xted; | |
public interface SomeInterface { | |
String name(); | |
Integer age(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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