Checking HTTP Status Code in Selenium

Pete picture Pete · Mar 1, 2010 · Viewed 49.9k times · Source

How to get the HTTP status code in Selenium?

E.g. so I can test that if the browser requests /user/27 and no user with ID=27 exists, an HTTP 404 is returned?

My primary interest is Selenium RC, but if someone knows the answer for "normal" selenium, I can probably easily translate it into RC.

/Pete

Answer

AutomatedTester picture AutomatedTester · Mar 1, 2010

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.