HtmlUnitDriver - Non GUI Browser in Selenium

What is HtmlUnitDriver?

HtmlUnitDriver is headless driver providing non-GUI implementation of Selenium WebDriver. It is based on HtmlUnit, fastest and light-weight browser implemented in Java.

WebDriver driver = new HtmlUnitDriver();

Advantages of HtmlUnitDriver

  1. Test execution using HtmlUnitDriver is very fast. Since, it is the fastest implementation of Selenium WebDriver.
  2. Being headless and fast, it is ideal choice for web scrapping.
  3. Its browser - htmlUnit is Java based. Hence, it is platform independent.
  4. It also supports JavaScript execution through in-built Rhino javascript engine.

Limitations of HtmlUnitDriver

  1. Being non-GUI makes it difficult to create scripts and debug issues while scripting.
  2. The Rhino javascript engine of HtmlUnitDriver make it unsuitable to emulate other popular browser's javascript behaviour.

Code Snippet for HtmlUnitDriver

The script creation in HtmlUnitDriver is similar to scripting in any other driver, only the driver instantiation part is different. The below script, when executed will run the test in non-GUI mode without opening any browser.

public class HtmlUnitDriverDemo {
	
	@Test
	public void htmlUnitDriverTest(){
		
		//Instantiating HtmlUnitDriver
		WebDriver driver = new HtmlUnitDriver();
					      
		//Navigate to ArtOfTesting.com		
		driver.get("http://www.artoftesting.com");
		
		//Printing page title
		System.out.println(driver.getTitle());

	}
	
}