Search code examples
cssunit-testingregression-testing

Regression testing for styling and layout of web applications


I realise this is a non-trivial task, but is there a way to regression test the styling and rendered layout of a web application?

I've found it straightforward to unit test and regression test functionality, both server-side and client-side.

However, a frustrating issue I've run into are CSS changes made to fix one layout issue that break the layout and styling on a different page. The only way I know how to detect these is to manually view every page in an application, and compare it with my own expectations, but obviously this can be burdensome and expensive when an application can have dozens of pages. Has there been any research using image processing or other techniques to detect these kinds of problems automatically?


Solution

  • Actually, one of the hidden gems of Selenium is that you can use it to take screen captures of the browser. Then using a technique as described in Find differences between images using C#, you can highlight the differences between previous snapshots.

    This example shows how to grab a screenshot of the homepage and then create a difference image. With a little extra tinkering, you can use the same technique to count the pixels that are different.

    [Test]
    public void CompareHomePageToPrevious()
    {
        string fileName = Path.Combine(Environment.CurrentDirectory, "homepage.bmp");
        var selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://mywebsite");
        selenium.Start();
        selenium.Open("/");
        selenium.CaptureEntirePageScreenshot(fileName, "");
    
        // Load current and previous captures
        var current  = new Bitmap(filename);
        var previous = new Bitmap(_previousHomepageImage);
    
        // Find all pixels that are the same and make them pink
        Bitmap diff = ImageTool.GetDifferenceImage(current,previous,Color.Pink);
        diff.MakeTransparent(Color.Pink);
    
        // Save the image for viewing
        // or count the number of different
    }
    

    Selenium is a really interesting choice because it's cross-platform and cross-browser, meaning that you can capture screens of different browsers. You can use this technique to compare snapshots between builds or to compare between browsers.