Selenium is an open-source web automation tool that supports many user actions to perform testing in the web browser.
Why Headless Browser?
Executing the automation code to run on a web browser is used to perform UI testing and functional testing, But sometimes while we run our automation scripts on the browser the page takes time to load all the UI and images which causes errors and is more time-consuming. Also, most of the CI systems are using the non-UI mode, so we need to automate scripts for Non-UI mode, that’s why the Headless browser comes into use.
Headless Browser
Headless browsers are acts like real web browsers but without any GUI, The automation script is executed like any other browser but it does not display any UI, they execute only in the background. In selenium, we have support for the Headless browser using “HtmlUnitDriver”, it executes the script in the non-GUI mode.
Running Selenium test cases using HTMLUnitDriver
To implement the selenium script in Headless Mode, add the dependency for “HtmlUnitDriver” from the maven repository.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<version>4.5.0</version>
</dependency>
Import the dependency class
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
Create an instance for HtmlUnitBrowser
HtmlUnitDriver driver=new HtmlUnitDriver();
Example
In this example, we run the selenium script in Headless Mode.
- Launch the neveropen website in non-GUI mode.
- Get the title of the page.
Java
import org.openqa.selenium.htmlunit.HtmlUnitDriver; public class Geeks { @Test public void geekforgeeks() { HtmlUnitDriver driver = new HtmlUnitDriver(); System.out.println( "Title of the page is " + driver.getTitle()); driver.close(); } } |
Output:
This code will open the browser in headless mode and perform the testing.