如何在 Selenium 中获取 HTTP 状态码?
例如,我可以测试如果浏览器请求 /user/27 并且不存在 ID=27 的用户,则返回 HTTP 404?
我的主要兴趣是 Selenium RC,但如果有人知道“正常”硒的答案,我可能可以轻松地将其翻译成 RC。
/皮特
如何在 Selenium 中获取 HTTP 状态码?
例如,我可以测试如果浏览器请求 /user/27 并且不存在 ID=27 的用户,则返回 HTTP 404?
我的主要兴趣是 Selenium RC,但如果有人知道“正常”硒的答案,我可能可以轻松地将其翻译成 RC。
/皮特
对于此类测试,这可能不是 Selenium 的最佳用途。当你可以做并且有一个更快的运行测试时,没有必要加载浏览器
[Test]
[ExpectedException(typeof(WebException), UserMessage = "The remote server returned an error: (404) Not Found")]
public void ShouldThrowA404()
{
HttpWebRequest task; //For Calling the page
HttpWebResponse taskresponse = null; //Response returned
task = (HttpWebRequest)WebRequest.Create("http://foo.bar/thiswontexistevenifiwishedonedayitwould.html");
taskresponse = (HttpWebResponse)task.GetResponse();
}
如果您的测试在 404 Selenium 期间重定向到另一个页面,则可以检查最终页面是否符合您的期望。
由于 Selenium 2 包含 HtmlUnit,您可以使用它来直接访问响应。
public static int getStatusCode(long appUserId) throws IOException {
WebClient webClient = new WebClient();
int code = webClient.getPage(
"http://your.url/123/"
).getWebResponse().getStatusCode();
webClient.closeAllWindows();
return code;
}
我知道这是一个令人震惊的黑客,但这就是我所做的:
protected void AssertNotYellowScreen()
{
var selenium = Selenium;
if (selenium.GetBodyText().Contains("Server Error in '/' Application."))
{
string errorTitle = selenium.GetTitle();
Assert.Fail("Yellow Screen of Death: {0}", errorTitle);
}
}
它可以在我需要它的情况下完成工作,尽管我接受它并不理想......
您可能想查看 captureNetworkTraffic() 调用。现在它只能在 Firefox 上可靠地工作,除非您手动设置 IE/Safari/etc 以通过端口 4444 代理流量。
要使用它,只需调用 selenium.start("captureNetworkTraffic=true"),然后稍后在您的脚本中,您可以调用 selenium.captureNetworkTraffic("...") 其中“...”是“plain”,“xml ”,或“json”。
我还没有尝试过,但如果你不介意将自己限制在 Firefox 上,并安装 Firebug 和 Netexport,那么 Selenium 可以访问页面状态代码(以及 Firebug 的 Net 面板中的所有其他内容):http://selenium .polteq.com/en/using-netexport-to-export-firebugs-net-panel/
如果一切都失败了,您可以在测试期间调整服务器端代码,以将页面中的 HTTP 状态作为元素输出:
例如,在我的 403 Permission Denied 页面上,我有:
<h1 id="web_403">403 Access Denied</h1>
可以通过 WebDriver API 轻松检查:
public boolean is403(WebDriver driver) {
try {
driver.findElement(By.id("web_403"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
https://rogerkeays.com/how-to-get-the-http-status-code-in-selenium-webdriver
试试这个,人们
WebClient wc = new WebClient();
int countRepeats = 120; // one wait = 0.5 sec, total 1 minute after this code
boolean haveResult = false;
try {
HtmlPage pageHndl = wc.getPage(Urls);
for(int iter=0; iter<countRepeats; iter++){
int pageCode = pageHndl.getWebResponse().getStatusCode();
System.out.println("Page status "+pageCode);
if(pageCode == 200){
haveResult = true;
break;
}
else{
Thread.sleep(500);
}
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}