检查Selenium中的HTTP状态代码

Pet*_*ete 44 selenium selenium-rc

如何在Selenium中获取HTTP状态代码?

例如,我可以测试一下,如果浏览器请求/ user/27并且没有ID = 27的用户,则返回HTTP 404?

我的主要兴趣是Selenium RC,但如果有人知道"正常"硒的答案,我可以很容易地将其翻译成RC.

/皮特

Aut*_*ter 10

对于这种类型的测试,这可能不是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();
}
Run Code Online (Sandbox Code Playgroud)

如果您的测试在404 Selenium期间重定向到另一个页面,则可以检查最终页面是否符合您的预期.


小智 6

我知道这是一个令人震惊的黑客,但这就是我所做的:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

它在我需要的情况下完成工作,虽然我接受它并不理想......


Sot*_*jor 5

由于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;
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这不适用于Selenium的C#版本. (5认同)

归档时间:

查看次数:

46675 次

最近记录:

8 年,7 月 前