我正在尝试从集成层隔离由Selenium(java绑定)驱动的UI测试。我想拦截通过浏览器的xhr调用并发回模拟响应。
我尝试配置代理(使用browsermob),可以看到请求通过了它。但是现在我不确定如何通过拦截xhr调用来返回模拟响应。
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
proxy.addRequestFilter((request, content, messageInfo) -> {
if (messageInfo.getOriginalUrl().contains("v1/listings/closing.json")) {
String messageContents = content.getTextContents();
System.out.println("messageContents:: " + messageContents);
}
return null;
});
try {
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
}
DesiredCapabilities seleniumCapabilities = new DesiredCapabilities();
seleniumCapabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
ChromeOptions options = new ChromeOptions();
options.merge(seleniumCapabilities);
webDriver = new ChromeDriver(options);
在对真实/实时网站而不是本地主机进行测试时,我希望将模拟响应提供给UI。
答案 0 :(得分:0)
使用代理。 addResponseFilter((response,contents,messageInfo)方法
示例:
proxy.addResponseFilter((response, contents, messageInfo) -> {
if (/*...some filtering criteria...*/) {
contents.setTextContents("This message body will appear in all responses!");
}
});
您可能会考虑使用赛普拉斯将UI测试与集成测试隔离开来。使用赛普拉斯-夹具模拟响应很容易
答案 1 :(得分:0)
Short-circuiting the request with mocked response and not let it pass through using Selenium.
String stubResponse = { mocked json response body };
proxy.addRequestFilter(new RequestFilter() {
@Override
public HttpResponse filterRequest(HttpRequest request, HttpMessageContents contents, HttpMessageInfo messageInfo) {
if (request.getUri().contains("/v1/listings/closing.json")) {
//Use DefaultFullHttpResponse for posting the json body
HttpResponse httpResponse = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
//Close the connection so it doesn't pass through
httpResponse.headers().add("CONNECTION", "Close");
//Specify the content-type and charset
httpResponse.headers().add("Content-Type", "application/json; charset=UTF-8");
//other headers if necessary
httpResponse.headers().add("Access-Control-Allow-Headers", "");
httpResponse.headers().add("Access-Control-Allow-Origin", "*");
httpResponse.headers().add("Access-Control-Expose-Headers","");
//replace the body
HttpObjectUtil.replaceTextHttpEntityBody((FullHttpMessage) httpResponse, stubResponse);
return httpResponse;
}
return null;
}
});