Objective

Run Selenium tests in headless mode (i.e. without opening browser) with inbuilt HtmlUnitDriver.

This is very easy and just 2 line code.

Test1.java

Create a java class Test1.java and paste following code in it.

import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.WebDriver;

public class Test1 {
	public static WebDriver driver;

	@Test
        public void FirstTest {
        driver = new HtmlUnitDriver(true);
        driver.get("https://google.com")
        }
}

And we are done 🙂

Notice that we have used true in HtmlUnitDriver, this is done to enable javascript support.

Ignoring Warnings

You’ll notice that once you Run the above code you’ll see warnings in your console like below

Aug 07, 2017 1:06:51 PM com.gargoylesoftware.htmlunit.html.HtmlScript isExecutionNeeded
WARNING: Script is not JavaScript (type: application/ld+json, language: ). Skipping execution.
Aug 07, 2017 1:06:52 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
INFO: JQMIGRATE: Migrate is installed, version 1.4.1
Aug 07, 2017 1:06:54 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Aug 07, 2017 1:06:55 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Aug 07, 2017 1:06:55 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.

To ignore these warnings, simply configure your logger to do so as below

import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.WebDriver;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test1 {
	public static WebDriver driver;
	static Logger log = Logger.getLogger("com.gargoylesoftware");

	@Test
     public void FirstTest {
     	log.setLevel(Level.OFF);
        driver = new HtmlUnitDriver(true);
        driver.get("https://google.com")
        }
}

And we are done! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s