Run ChromeDriver with Chrome Driver Service to reduce script execution time significantly

Google_ChromeSelenium
What we do:

We can start ChromeDriver by instantiating webdriver instance in the following way.

WebDriver driver=new ChromeDriver();

or some people start ChromeDriver by mentioning the path to the ChromeDriver executable when executable is not in System path:

System.setProperty(“webdriver.chrome.driver”, “/path/to/chromedriver”);

WebDriver driver = new ChromeDriver();

Problem:

Each time ChromeDriver is instantiated ChromeDriver server starts and stopped once driver.quit() is called. If we have a large set of test suites generally we close and open Chrome browser multiple times. So by this process ChromeDriver server is started and stopped that much of times which consumes a significant amount of time.

Solution:

This is possible to start ChromeDriver Service which avoids starting and stopping ChromeDriver server multiple times.

Benefits:
1.  ChromeDriver server is started only once
2. Chrome browser can be relaunched in a very lesser amount of time than the previous option
3.  No Console logs like starting server , stopping server etc while running script (only once logged when server started)

How to do it?

private static ChromeDriverService service;
private WebDriver driver;

@BeforeClass
public static void createAndStartService() {
service = new ChromeDriverService.Builder()
.usingChromeDriverExecutable(new File(“path/to/my/chromedriver”))
.usingAnyFreePort()
.build();
service.start();
}

@AfterClass
public static void createAndStopService() {
service.stop();
}

@Before
public void createDriver() {
driver = new RemoteWebDriver(service.getUrl(),
DesiredCapabilities.chrome());
}

@After
public void quitDriver() {
driver.quit();
}

Switch to ChromeDriver Service , save time!!

Happy Testing!!