Headless WebDriver Testing using HtmlUnitDriver
In this tutorial, we will see what headless testing is and how to implement it using HTMLUnitDriver.
A headless browser is one which doesn’t have a head(duh!) or in other words a GUI. It doesn’t open up any browser or interrupt any activities on the running system.
This is preferred if you are running the tests in a system where you don’t have any browsers installed or on a headless server. Some other scenarios I can think of is for personal uses: like if you want to open some web pages and extract data from it, or in the case of bloggers – if you want to automatically share a blog post to social networking sites after you have published the post.
Since we can simulate any browser using HTMLUnitDriver, this can also be used for testing across various browsers on a server which doesn’t have any/all of them.
There are a few ways of implementing headless mode for Selenium WebDriver
HtmlUnitDriver is the fastest and most lightweight implementation of WebDriver. It is based on HtmlUnit which is a java based implementation of a browser without a GUI.
In this tutorial, we focus on HTMLUnitDriver. If you are interested in GhostDriver, check out this article by AssertSelenium.
As mentioned above, it’s the fastest and most lightweight implementation of WebDriver.
Now, let’s go into the fun part.
The best way to create a headless webdriver script is to create the script using any browser implementation – FirefoxDriver or ChromeDriver etc. This way you can make sure that the script works fine.
Once that is done, you can make the change in initialization part to convert it to HtmlUnitDriver. Please note that if you application behaves differently for GUI or headless mode, you have to make the appropriate changes.
For running webdriver in headless mode, we have to initialize as shown below.
HtmlUnitDriver driver = new HtmlUnitDriver();
// or in single line
driver = new HtmlUnitDriver(true);
Even though the driver object is not of WebDriver interface, all its operations are available.
We can also emulate a specific browser as below.
driver = new HtmlUnitDriver(BrowserVersion.CHROME);
You have a list of browser options available
We can also set DesiredCapabilities as shown below.
DesiredCapabilities capabilities = new DesiredCapabilities();
// set capabilities
driver = new HtmlUnitDriver(capabilities);