Automated Tester

.science

This content shows Simple View

Status Code

Checking link status in C#

Sometimes you need to test an application that has external links or have the need to check links and it doesn’t make a whole lot of sense to physically visit these places and verify that something has loaded on it because it is way out of your control and that site could change at any given moment, making your tests flaky.

One way to circumvent this is to check the link status code of a given link by sending a http request and returning the status code. We can then parse this to a string and make an assertion based against it. The code below does all the heavy lifting.

        public HttpStatusCode GetHeaders(string url)
        {
            HttpStatusCode result = default (HttpStatusCode );

            var request = HttpWebRequest.Create(url);
            request.Method = "HEAD";
            using ( var response = request.GetResponse() as HttpWebResponse)
            {
                if (response != null)
                {
                    result = response.StatusCode;
                    response.Close();
                }
            }

            return result;
        }

So in our step definition all we need to do is assert the returned status code against what we are expecting it to be whether it be a 200 OK, 404, 500 etc.

We can now call this and make an assertion on the retrieved link status in our step definition files.

        var expectedStatus = VerifyPages.HttpStatusOk;
        var facebookLink = UrlConsts.Facebook;
        var facebookStatus = Page.GetHeaders(facebookLink).ToString();
        Assert.AreEqual(expectedStatus, facebookStatus);



top