Question: How to perform Headless Testing using HtmlUnitDriver in Selenium?
Answer:
Basically, headless testing is, running a script in the background without any visual of the browser. In simple words, this process doesn't need any browser. This method can be used on the machines which don't have any browser installed on them.
This technique has been used for simple websites to get data or input from them without interfering to the user in a quick and easy way, as the user doesn't have to wait for launching the browser or loading the URL etc.
Example:
Reference URL: https://seleniumqna.blogspot.in/
STEPS:
- Create an object of HtmlUnitDriver.
- Launch above mentioned URL using the driver.
- Getting Window Title after launching the URL.
- Getting Post Content (Website Content)
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.Test;
public class HtmlUnitExample
{
@Test(description="Headless Testing using HtmlUnitDriver")
public void getPostContent() throws InterruptedException, IOException
{
// To turn off all the HTMLUnit warnings from console output.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
System.out.println("Headless Testing using HtmlUnitDriver Execution Start");
WebDriver driver=new HtmlUnitDriver(); // Step #1
driver.get("https://seleniumqna.blogspot.in/"); // Step #2
System.out.println("Window Title : "+driver.getTitle()); // Step #3
By locator_post=By.xpath("//*[contains(text(),'Question:')]/../..");
List<WebElement> postList=driver.findElements(locator_post);
for (WebElement postData : postList)
{
System.out.println(postData.getText()); // Step #4
}
driver.quit();
}
}
Conclusion:
The user can observe the difference of the time and speed of running the same script on any other browser such as Chrome, Firefox etc. and on the headless browser using HtmlUnitDriver.
Disadvantages:
1. We can't use this technique for complex websites.
2. HtmlUnitDriver doesn't support screenshot functionality. The PhantomJS Driver supports screenshots functionality as well. Will share the POST for the same very soon.
3. Debugging of the script is also too complex as compared to non-headless technique.
Please do comment and share the post with your friends and colleagues. For any query or question, you can also mail us at ashu.kumar940@gmail.com.
Other Blogs:
https://agilehelpdoc.blogspot.in/