How to run Chrome tests in headless mode in Selenium4

HOME

This tutorial explains the steps to run the Selenium tests in Chrome browser in headless mode. We are going to run the tests in Selenium 4.

Add the below dependencies to pom.xml or build.gradle.

Add the below dependencies to the project. I have added the Junit dependency because I want to add an assertion and create a test method.

<dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.9.1</version>
 </dependency>

 <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.9.2</version>
            <scope>test</scope>
 </dependency>

What is a headless browser?

A headless browser is like any other browser but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console.

Headless browser testing is generally faster when compared to actual UI testing as it doesn’t wait for the whole page to render before performing any action.

The traditional way is to add –headless, and since version 96, Chrome has a new headless mode that allows users to get the full browser functionality (even run extensions). Between versions 96 to 108 it was  –headless=chrome, after version 109, it is –headless=new.

The complete program looks like as shown below:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class HeadlessChrome_Demo {

    public ChromeDriver driver;

    @Test
    public void test() {

        // Create an object of Chrome Options class
        ChromeOptions options = new ChromeOptions();

        // pass the argument -–headless and maximize to Chrome Options class.
        options.addArguments("--start-maximize");
        options.addArguments("--headless=new");

        // Create an object of Chrome Driver class and pass the Chrome Options object as
        // an argument
        driver = new ChromeDriver(options);

        System.out.println("Executing Chrome Driver in Headless mode..");
        driver.get("https://duckduckgo.com/");

        String titlePage = driver.getTitle();
        System.out.println("Title of Page :" + titlePage);
        Assertions.assertEquals("DuckDuckGo — Privacy, simplified.",titlePage);
        
        // Close the driver
        driver.close();

    }

}

The output of the above program is

Congratulations!! We are able to run Chrome tests in Selenium in headless mode.

Leave a comment