在 Java 中,**Proxy(代理)**通常有两种常见含义:
下面我分别说明 如何测试 Java 代理(尤其是动态代理),并给出示例。
public interface UserService {
String getName(int id);
}
public class UserServiceImpl implements UserService {
@Override
public String getName(int id) {
return "User-" + id;
}
}
import java.lang.reflect.*;
public class LogHandler implements InvocationHandler {
private final Object target;
public LogHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("after");
return result;
}
}
UserService proxy = (UserService) Proxy.newProxyInstance(
UserService.class.getClassLoader(),
new Class[]{UserService.class},
new LogHandler(new UserServiceImpl())
);
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ProxyTest {
@Test
void testProxy() {
UserService proxy = (UserService) Proxy.newProxyInstance(
UserService.class.getClassLoader(),
new Class[]{UserService.class},
new LogHandler(new UserServiceImpl())
);
String result = proxy.getName(1);
assertEquals("User-1", result);
}
}
System.out.println(proxy instanceof Proxy); // true
System.out.println(Proxy.isProxyClass(proxy.getClass())); // true
如果代理里有日志、事务、权限等逻辑:
@Test
void testProxyLogic() {
UserServiceImpl target = new UserServiceImpl();
LogHandler handler = new LogHandler(target);
UserService proxy = (UserService) Proxy.newProxyInstance(
UserService.class.getClassLoader(),
new Class[]{UserService.class},
handler
);
proxy.getName(2);
// 可结合 Mockito 或捕获 System.out 来验证日志
}
✅ 更专业做法:
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
System.out.println("before");
return proxy.invokeSuper(obj, args);
});
UserServiceImpl proxy = (UserServiceImpl) enhancer.create();
测试方式与 JDK 代理类似。
例如 HTTP 代理:
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8080");
测试方式:
curl / postman| 代理类型 | 测试重点 |
|---|---|
| JDK 动态代理 | 是否增强方法、返回值是否正确 |
| CGLIB | 是否拦截方法 |
| 网络 Proxy | 请求是否经过代理 |
如果你能提供:
我可以给你更精准的测试方案(甚至 Mock + 断言示例)。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。