Wednesday, July 8, 2015

Design Patterns - Driver Factory

One of the advantages of Selenium is it's support for multiple browsers. Mobile automation platforms like Appium support for Selenium. This makes Selenium a versatile library not only for multiple browsers, but also for mobile platforms.When a test needs to be performed on both browser and mobile, Selenium wins the title.

There are many approaches to utilize multi-browser support in Selenium. One of them is to centralize the Web Driver object creation based on configuration using Factory Pattern. Basically target browser name is configured in a properties file (Java world) or App.Config (C# world), and a factory method takes care of the web driver object creation based on configured value. 

In this solution, browser name (aka target browser) is stored against a key in a properties file. Test fixture (method with @Before annotation in TestNG/JUnit) calls a utility method to get driver instance. This utility method reads the configured browser name from configuration file, and calls web driver object creation method of Driver Factory class.

Such approaches of centralizing the web driver creation through a configuration parameter helps when tests are integrated with CI solution like Jenkins to run tests in multiple browsers. 






Properties File: This file contains key value pairs. One of the keys is "browser name" with possible values FireFox, or IE, or Chrome.

Driver Map: Driver Map can be a singleton class or a regular utility class with a method to read value of "browser name" key in properties file and calls driver creation method in Driver Factory class. Driver Map being a Singleton is helpful if you want to create the web driver instance once for all tests or when you want your page object classes and other object handling static methods to access the web driver instance. (I will cover passing web driver instance to various classes in another post). The same singleton can be used to maintain both web driver instance of browser, as well as Appium (mobile) driver in case you are using Appium.

Driver Factory: A simple method with a parameter browser type and a switch case to handle Web Driver object creation. This method returns instance of Web Driver which is eventually used in selenium tests.

2 comments:

  1. Good and useful concept. Is this possible to extend this configurability for a target machine also. Like if I want to execute on specific machine for Specific browser

    ReplyDelete
    Replies
    1. Thanks Subbu. It is possible to configure to run tests on a specific browser on a specific machine using Selenium Grid. In case you want to run specific tests on a specific browser, same can be achieved using parameters in TestNG.

      Delete