How to Open a Browser in Headless Mode in Selenium using Java?
Last Updated :
25 Jan, 2025
Headless testing has become a significant trend in modern web automation, offering numerous advantages for developers and testers. In Selenium, running tests in headless mode allows browsers to operate without the graphical user interface (GUI). This article delves into the concept of headless browser testing, its importance, how to run browsers in headless mode in Selenium with Java, and the benefits and limitations of headless testing.
What is Headless Browser Testing?
Headless browser testing is a method of performing automated tests in web browsers and it doesn’t require the GUI. Headless browsers do not display the complete browser window, instead, it is used to load pages and execute JavaScript. It is particularly valuable if the special integration (CI) or an automated testing environment does not require a GUI
Why is Headless Execution Important?
- Speed: Headless browsers generally perform better in comparison to GUI browsers because the latter do not focus on graphics rendering. This leads to faster tests run through.
- Resource Efficiency: Many tests can be run from the command line, and devoid of a GUI, the environment puts a smaller demand on the station’s hardware.
- CI/CD Integration: A majority of CI/CD pipelines deploy GUI for automation and some require a non-GUI response, particularly for tests. These remain fluid as headless testing accommodates itself into these processes easily.
- Stability: Headless tests for example have been known to help minimize the problem of flaky tests related to GUI interactions due to timing problems.
Running Headless Mode in Selenium for Chrome
Selenium provides the option to run the Chrome browser in headless mode with minimal configuration. To enable headless mode in Chrome, we use the ChromeOptions
class and set the --headless
flag.
Step-by-Step Implementation:
- Set up ChromeDriver: Ensure that you have the correct version of ChromeDriver installed for your version of Chrome. You can download it from the official website.
- Create the WebDriver instance in headless mode:
Java
package browser_specific.headless;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import actions.BaseTest;
public class HeadlessChromeTest extends BaseTest {
private WebDriver driver;
@BeforeClass
public void setUp() {
// Configure ChromeOptions for headless mode
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new"); // Use new headless mode
options.addArguments("--disable-gpu"); // Recommended for headless execution
options.addArguments("--window-size=1920,1080"); // Set specific window size
driver = new ChromeDriver(options);
}
@Test
public void testHeadless() {
// Navigate to the webpage
driver.get("https://bonigarcia.dev/selenium-webdriver-java/web-form.html");
// Assert that the title contains "Selenium WebDriver"
assertTrue(driver.getTitle().contains("Selenium WebDriver"), "Title does not match the expected value");
}
@AfterClass
public void tearDown() {
// Close the browser
if (driver != null) {
driver.quit();
}
}
}
Output:
Headless Mode in Selenium for ChromeExplanation:
- The
ChromeOptions
object is used to set configurations for the Chrome browser. - The
--headless
argument is passed to run Chrome in headless mode. - The
--disable-gpu
argument is used to avoid potential issues related to graphics rendering in headless mode. - Selenium then interacts with the page, even though Chrome is running without a visual interface.
Running Headless Mode in Selenium for Firefox
Similar to Chrome, Firefox can also be run in headless mode using the FirefoxOptions
class. Here's how you can set up Firefox for headless testing:
Step-by-Step Implementation:
Java
package browser_specific.headless;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import actions.BaseTest;
public class HeadlessFirefoxTest extends BaseTest {
private WebDriver driver;
@BeforeClass
public void setUp() {
// Configure FirefoxOptions for headless mode
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--headless"); // Enable headless mode
options.addArguments("--disable-gpu"); // Recommended for headless execution
options.addArguments("--window-size=1920,1080"); // Set specific window size
driver = new FirefoxDriver(options);
}
@Test
public void testHeadlessFirefox() {
// Navigate to the webpage
driver.get("https://bonigarcia.dev/selenium-webdriver-java/web-form.html");
// Assert that the title contains "Selenium WebDriver"
assertTrue(driver.getTitle().contains("Selenium WebDriver"), "Title does not match the expected value");
}
@AfterClass
public void tearDown() {
// Close the browser
if (driver != null) {
driver.quit();
}
}
}
Output:
headless mode using the FirefoxExplanation:
- The
FirefoxOptions
object is used to configure Firefox's settings. - The
setHeadless(true)
method is used to enable headless mode. - Like the Chrome example, no GUI will be launched, but the WebDriver will interact with the webpage and run the necessary tasks.
Running Headless Mode in Selenium for Edge
Microsoft's Edge browser also supports headless mode, though the process is slightly different due to the Edge WebDriver. Here's how you can run tests in headless mode with Edge:
Step-by-Step Implementation:
Java
package browser_specific.headless;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import actions.BaseTest;
public class HeadlessEdgeTest extends BaseTest {
private WebDriver driver;
@BeforeClass
public void setUp() {
// Configure EdgeOptions for headless mode
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new"); // Use new headless mode
options.addArguments("--disable-gpu"); // Recommended for headless execution
options.addArguments("--window-size=1920,1080"); // Set specific window size
driver = new EdgeDriver(options);
}
@Test
public void testHeadlessEdge() {
// Navigate to the webpage
driver.get("https://bonigarcia.dev/selenium-webdriver-java/web-form.html");
// Assert that the title contains "Selenium WebDriver"
assertTrue(driver.getTitle().contains("Selenium WebDriver"), "Title does not match the expected value");
}
@AfterClass
public void tearDown() {
// Close the browser
if (driver != null) {
driver.quit();
}
}
}
Output:
This code will open the browser in headless mode and perform the testing.
headless mode with EdgeBenefits of Selenium Headless Testing
- Faster Execution: Which was discussed earlier, headless tests are faster in comparison to regular tests.
- Lower Resource Consumption: Headless tests consume less computational power and, therefore, are suitable for systems with lower performance.
- Suitable for Continuous Integration: Can easily be integrated to CI/CD systems.
- Simplifies Testing Environments: Simplifies test scenarios in a setting where GUIs are a nuisance to the testing process.
Limitations of Selenium Headless Testing
- Limited Debugging: Debugging becomes a process a bit more cumbersome again because of the absence of a graphical interface.
- Potential Differences in Behavior: It also means that in headless mode web applications may have different behavior to full browsers, meaning that if tests are run in this mode, the results can be different from those obtained when tests are run in a full browser.
- Limited Support for Certain Features: A few sophisticated operations may also fail to work properly such as – rendering CSS or JavaScript based web pages.
Conclusion
Automated testing of web applications with Selenium and headless browser is a useful approach to the optimization of a CI/CD process. As useful as it is, it is also important that developers understand its shortcomings. Thus, headless testing is one of the best tools for enhancing the tempo of web application testing.
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read