If you are involved in the web development, you most probably need sometimes to create redirects from one page to another. Thus, you need to test URL redirects. Usually, it is OK to check them only once when they are created. However, the best practice is to create an automation regression validation engine- for example via integration tests. In this publication, I will show you how to test URL redirects via WebDriver and HttpWebRequests. The redirects checker engine will use Strategy Design Pattern, which will make the change of the validation algorithm easier without changing the core.

Test URL Redirects Configuration

I believe that the most straightforward way to configure redirects is via XML configuration.

In the above sample configuration, you can test more than one site. Under its node are placed the different redirects rules- the source page (from URL) and destination page (to URL). The engine supports partial and full URLs.

There are four classes to which the above configuration is deserialized once it is read.

Test URL Redirects Service

The main class that is used to test URL redirects is the RedirectService. It accepts IRedirectStrategy, which defines the base redirect engine algorithm methods.

The InitializeRedirectUrls transforms the previously mentioned XML configuration to the shown C# classes. The primary method of the service- TestRedirects is used to test URL redirects calling the NavigateToFromUrl engine’s function that returns the destination URL. After that, the service compares the setup target URL and the output one. It is repeated for all URLs from the XML configuration. If there are any mismatches, an exception is thrown. The RedirectsService should be called wrapped in using statement in order the engine to be able to be disposed.

The interface of the strategy design pattern contains only three methods.

Test URL Redirects via WebDriver

The first implementation of the redirects strategy uses WebDriver test framework.

The strategy can be extended to specify a different browser, however for the example I’m using Firefox. In the Initialize method, a new driver instance is created and disposed in the Dispose method. The core method navigates to the configured URL, and when the page is completely loaded it saves the destination URL and return it.

Test URL Redirects via HttpWebRequest

The fastest way to test HTTP redirects is via HttpWebRequest C# class.

A simple HTTP HEAD request is created, and when its response is returned, the destination URL is extracted from it. There is no need to initialize or dispose anything in this method.

Test URL Redirects Usage in Integration Tests

If you need to change the redirects engine implementation, pass the another implementation to the constructor of the RedirectService.