Checking HTTP Status Code in Selenium Checking HTTP Status Code in Selenium selenium selenium

Checking HTTP Status Code in Selenium


This might not be the best use of Selenium for this type of test. There is unnecessary need to load a browser when you could do and have a faster running test

[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();}

If your test is redirecting to another page during a 404 Selenium could check the final page has what you expect.


I know this is a shocking hack, but this is what I've done:

    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);        }    }

It gets the job done in the situation I needed it for, although I accept it's not ideal...


Since Selenium 2 includes HtmlUnit, you can utilize it in order to get access to the response directly.

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;}