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
Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.
You can obtain the response code in Java by using URL. openConnection() and HttpURLConnection. getResponseCode() : URL url = new URL("http://exampleurl.ex"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.
We can get the HTTP response code in Selenium webdriver with Java. Some of the response codes are – 2xx, 3xx, 4xx and 5xx. The 2xx response code signifies the proper condition, 3xx represents redirection, 4xx shows resources cannot be identified and 5xx signifies server problems.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With