对于集成测试,我需要在 java 服务客户端中模拟特定方法,而不破坏其中的其余信息。它没有自构造函数,所以这样的解决方案是不可能的:
private DBClient mockClient = new DBClient(alreadyExistingClient){
@Override
void deleteItem(Item i){
//my stuff goes here
}
};
有没有办法模拟 deleteItem 方法,以便将凭据、端点等保留在现有的 DBClient 对象中?
编辑:mockito 在这种情况下不可用
您可以使用动态代理来拦截您想要的任何方法调用,这样您就可以决定是调用真正的方法还是执行您想要的任何操作。
这是如何拦截该方法的示例Set.add()
,你可以做同样的事情deleteItem()
package example.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
public class SetProxyFactory {
public static Set<?> getSetProxy(final Set<?> s) {
final ClassLoader classLoader = s.getClass().getClassLoader();
final Class<?>[] interfaces = new Class[] {Set.class};
final InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (method.getName().equals("add")) {
System.out.println("add() intercepted");
// do/return whatever you want
}
// or invoke the real method
return method.invoke(s, args);
}
};
final Object proxy = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
return (Set<?>) proxy;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)