Sunday, October 18, 2015

Flexible tests with DataProviders and Strategies

DataProviders

TestNG DataProviders are a powerful way to parameterize test classes, allowing you to run a single test method many times with different inputs.

For example, say we'd like to assert that a group of web search engines have a 'search box' on their home page, but because they're maintained by different companies, don't have a common HTML locator. Here we use a DataProvider to maintain a list of URLs and their corresponding 'search box' IDs, go to the URL and assert the search box is visible.

However, let's say that one day DuckDuckGo adds an ad to their main page that hides the 'search box' until you close it, but we still want to assert that the 'search box' is still there. We could add some complexity to our @Test method that clicks the ad, but only for duckduckgo.com, or we could add a second DataProvider and a second @Test that does the additional step. Both of these make the test awful to read, unfortunately.

Using Strategies

I've found that using DataProviders to provide assertion Strategies is a great way to solve this type of problem. Here we create interface SearchEngine, and implementing classes DefaultSearchEngine and DuckDuckGo to abstract the varying behavior away of preparing the page from the test method. And then provide a SearchEngine to the test method using searchBoxProvider.