In the absence of a mock framework, java.lang.reflect.Proxy is your best bet. If you've never used it before, you can create a dynamic object which implements a set of interfaces, and you use the InvocationHandler to check each method call and decide what to do. This is a very powerful technique (and not limited to testing), as you can delegate method calls to other objects, etc.... It also insulates you from certain interface changes when you do this sort of delegation, as you don't declare each method. It adapts to the interface at runtine.
public static interface MyIntf {
String foo(String arg1);
}
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("foo") &&
method.getParameterTypes().length == 1 &&
method.getParameterTypes()[0] == String.class) {
// do your mocking here. For now i'll just return the input
return args[0];
}
else {
return null;
}
}
};
MyIntf myintf = (MyIntf) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { MyIntf.class },
invocationHandler);
System.out.println(myintf.foo("abc"));