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


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.

Comments

  1. Very practical and useful approach of using java 1.8 in test automaton.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to mock a response in Selenium

Some useful links for testing

Generic Checklist in case you want to consider Cypress