Apply Java 8 features in Test Automation - Scenario 2
As we know Selenium-webdriver is a UI automation library that supports a lot of browsers. In automation framework, we have to provide a capability where based on the input, aa specific browser should be launched. So if you see the problem statement, it gives an idea to apply Factory Design Pattern.
So let's try to implement and understand it via code. Here we will be using Java 8 - Supplier
Let's create a class DriverFactory
Now wherever you need a browser, just order this DriverFactory as below
So let's try to implement and understand it via code. Here we will be using Java 8 - Supplier
Let's create a class DriverFactory
public class DriverFactory { private static final Supplier<WebDriver> chromeSupplier =() ->{ WebDriverManager.chromedriver().setup(); return new ChromeDriver(); }; private static final Supplier<WebDriver> firefoxSupplier =() ->{ WebDriverManager.firefoxdriver().setup(); return new FirefoxDriver(); }; private static final Map<String, Supplier<WebDriver>> MAP = new HashMap<>(); static { MAP.put("chrome",chromeSupplier); MAP.put("firefox",firefoxSupplier); } public static WebDriver getDriver(String browser){ return MAP.get(browser).get(); }}
Now wherever you need a browser, just order this DriverFactory as below
public class DriverfactoryTest { private WebDriver driver; @BeforeTest @Parameters("browser") public void setup(@Optional ("chrome")String browser){ this.driver=DriverFactory.getDriver(browser); }
Voila!!! we should be able to launch browser now.
Very practical and useful approach of using java 1.8 in test automaton.
ReplyDelete