How to pass parameter through testng.xml file to a test case?

We could define the parameters in the testng.xml file and then reference those parameters in the source files.
Create a java test class, say, ParameterizedTest.java and add a test method say parameterizedTest() to the test class. This method takes a string as input parameter. Add the annotation @Parameters(“browser”) to this method

// TestNG Interview Questions
public class ParameterizedTest {
@Test
@Parameters("browser")
public void parameterizedTest(String browser){
if(browser.equals("firefox")){
System.out.println("Open Firefox Driver");
}else if(browser.equals("chrome")){
System.out.println("Open Chrome Driver");
}
}
}
The parameter would be passed a value from testng.xml, which we will see in the next step.
We could set the parameter using the below syntax in the testng.xml file. 
<parameter name="browser" value="firefox"/>
Here, name attribute represents the parameter name and value represents the value of that parameter.

.
Hope this helps !!!

Difference between @BeforeTest and @BeforeMethod annotations in TestNG

This is most confusing point in testng. Let us understand the difference between them.
@BeforeTest Will be called before any Test only..
@BeforeMethod will be called before every method

Note that, not every method in a file is Test, but every Test in a file is a method.

In the above case the helper() method is only a method not a Test. Whereas toBeforeTest() and toBeforeMethod() are Test, since they are preceded with “@Test” annotation.

@BeforeTest will be executed only for the blocks of toBeforeTest() and toBeforeMethod().
Whereas @BeforeMethod will be executed for all the methods of toBeforeTest(), toBeforeMethod() as well as the helper() method

@BeforeTest is used to do setup related to bunch of tests written inside the tag as the author has mentioned.

@BeforeTest
@BeforeMethod
To execute a set-up method before any of the test methods included in the < test > tag in the testng.xml file.
To execute a set-up method before any of the test methods annotated as @Test.

Example Testng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">


<test name="test">
<classes>
<class name=".BeforetestandBeforemethod">
<methods>
<include name="toBeforeTest"></include>
<include name="toBeforeMethod"></include>
</methods>
</class>
</classes>
</test>

<methods>
</suite> <!-- Suite -->


Example Java code such as:

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class BeforetestandBeforemethod {

@BeforeTest
public void beforeTest() {
System.out.println("@BeforeTest");
}
@BeforeMethod
public void beforemethod(){
System.out.print("@BeforeMethod");
}

public void helper() {
System.out.println("Flow");
}

@Test
public void toBeforeMethod() {
helper();
System.out.println("BeforeMethod");
}

@Test
public void toBeforeTest() {
helper();
System.out.println("BeforeTest");
}

}
Execute code by TestNG, then the Output would be:
When run  <include name=”toBeforeTest”></include>

 

Run  <include name=”toBeforeMethod”></include>

Hope this helps !!!!


What are TestNG annotations?

Here is a quick overview of the annotations available in TestNG along with their attributes.
@BeforeSuite
@AfterSuite
@BeforeTest
@AfterTest
@BeforeGroups
@AfterGroups
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
Configuration information for a TestNG class:
@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to.
For after methods (afterSuite, afterClass, …): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.
@DataProvider
Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
Parameters for dataprovider –
a.       name
The name of this data provider. If it’s not supplied, the name of this data provider will automatically be set to the name of the method.
b.      parallel
If set to true, tests generated using this data provider are run in parallel. Default value is false.
@Factory
Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].
@Listeners
Defines listeners on a test class.
.
@Parameters
Describes how to pass parameters to a @Test method.
@Test  -> AnnotationMarks a class or a method as part of the test.
—  @Test (name=“example“,
                              description=“example test“,
                              expectedExceptions=IOException.class,
                              dataProvider=“dataProv“,
                              groups={“functional“,“stress“},
                              dependsOnGroups=“database“,
                              dependsOnMethods={“init“,“setup“},
                              enabled=true,
                              successPercentage=80,
                              timeout=10000,
                              invocationCount=10,
                              threadPoolSize=10,
                              sequential=true)

  Hope this helps !!!!

What is difference between TestNG and JUnit?

JUnit is shipped with most of the IDEs such as Eclipse and NetBeans. There are many testing frameworks being developed using JUnit.
TestNG is an open source framework. It supports parametrization, data driven testing, parallel execution. JUnit is not much flexible for these.
I prefer TestNG over JUnit. I have developed open source testing framework using TestNG for Selenium. You may want to have a look at it.
Now either you may choose from any of the frameworks available like JUnit & TestNG or you can design our own framework.
 Junit is a unit testing framework or the Java programming language. TestNG is specially designed to cover all types testing categories like Unit, Functional testing, Integration testing, End-to-end etc.
TestNG is a preferred framework of QA analysts as it allows you to generate test reports in both HTML and XML formats. TestNG enable you to group test cases easily which is not possible in JUnit. 
  1. Annotation Support
The main annotation differences between JUnit4 and TestNG are
1. In JUnit 4, we have to declare “@BeforeClass” and “@AfterClass” method as static method. TestNG is more flexible in method declaration, it does not have this constraints.
2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite, @Before/AfterTest, @Before/AfterGroup).
JUnit 4

1.  @BeforeClass
2.  public static void oneTimeSetUp() {
3.      // one-time initialization code
4.    System.out.println(“@BeforeClass – oneTimeSetUp”);
5.  }

TestNG
1.  @BeforeClass
2.      public void oneTimeSetUp() {
3.          // one-time initialization code
4.           System.out.println(“@BeforeClass – oneTimeSetUp”);
5.  }
2. Exception Test
The “exception testing” means what exception throws from the unit test, this feature is implemented in both JUnit 4 and TestNG.
JUnit 4
1.  @Test(expected = ArithmeticException.class)
2.  public void divisionWithException() {
3.    int i = 1/0;
4.  }
TestNG
1.  @Test(expectedExceptions = ArithmeticException.class)
2.  public void divisionWithException() {
3.    int i = 1/0;
4.  }
3. Ignore Test
The “Ignored” means whether it should ignore the unit test, this feature is implemented in both JUnit 4 and TestNG .
JUnit 4
1.  @Ignore(“Not Ready to Run”)
2.  @Test
3.  public void divisionWithException() {
4.    System.out.println(“Method is not ready yet”);
5.  }
TestNG
1.  @Test(enabled=false)
2.  public void divisionWithException() {
3.    System.out.println(“Method is not ready yet”);
4.  }
4. Time Test
The “Time Test” means if an unit test takes longer than the specified number of milliseconds to run, the test will terminated and mark as fails, this feature is implemented in both JUnit 4 and TestNG .
JUnit 4
1.  @Test(timeout = 1000)
2.  public void infinity() {
3.    while (true);
4.  }
TestNG
1.  @Test(timeOut = 1000)
2.  public void infinity() {
3.    while (true);
4.  }
5. Suite Test
The “Suite Test” means bundle a few unit test and run it together. This feature is implemented in both JUnit 4 and TestNG. However both are using very different method to implement it.
JUnit 4
The “@RunWith” and “@Suite” are use to run the suite test. The below class means both unit test “JunitTest1” and “JunitTest2” run together after JunitTest5 executed. All the declaration is define inside the class.
1.  @RunWith(Suite.class)
2.  @Suite.SuiteClasses({
3.          JunitTest1.class,
4.          JunitTest2.class
5.  })
6.  public class JunitTest5 {
7.  }
TestNG
XML file is use to run the suite test. The below XML file means both unit test “TestNGTest1” and “TestNGTest2” will run it together.
1.  <!DOCTYPE suite SYSTEM “http://beust.com/testng/testng-1.0.dtd” >
2.  <suite name=”My test suite”>
3.    <test name=”testing”>
4.      <classes>
5.         <class name=”com.fsecure.demo.testng.TestNGTest1″ />
6.         <class name=”com.fsecure.demo.testng.TestNGTest2″ />
7.      </classes>
8.    </test>
9.  </suite>
TestNG can do more than bundle class testing, it can bundle method testing as well. With TestNG unique “Grouping” concept, every method is tie to a group, it can categorize tests according to features. For example,
Here is a class with four methods, three groups (method1, method2 and method3)
1.  @Test(groups=”method1″)
2.  public void testingMethod1() {
3.    System.out.println(“Method – testingMethod1()”);
4.  }
5.   
6.  @Test(groups=”method2″)
7.  public void testingMethod2() {
8.    System.out.println(“Method – testingMethod2()”);
9.  }
10. 
11.@Test(groups=”method1″)
12.public void testingMethod1_1() {
13.  System.out.println(“Method – testingMethod1_1()”);
14.}
15. 
16.@Test(groups=”method4″)
17.public void testingMethod4() {
18.  System.out.println(“Method – testingMethod4()”);
19.}
With the following XML file, we can execute the unit test with group “method1” only.
1.  <!DOCTYPE suite SYSTEM “http://beust.com/testng/testng-1.0.dtd” >
2.  <suite name=”My test suite”>
3.    <test name=”testing”>
4.           <groups>
5.        <run>
6.          <include name=”method1″/>
7.        </run>
8.      </groups>
9.      <classes>
10.       <class name=”com.fsecure.demo.testng.TestNGTest5_2_0″ />
11.    </classes>
12.  </test>
13.</suite>
With “Grouping” test concept, the integration test possibility is unlimited. For example, we can only test the “DatabaseFuntion” group from all of the unit test classes.
6. Parameterized Test
The “Parameterized Test” means vary parameter value for unit test. This feature is implemented in both JUnit 4 and TestNG. However both are using very different method to implement it.
JUnit 4
The “@RunWith” and “@Parameter” is use to provide parameter value for unit test, @Parameters have to return List[], and the parameter will pass into class constructor as argument.
1.  @RunWith(value = Parameterized.class)
2.  public class JunitTest6 {
3.   
4.     private int number;
5.   
6.     public JunitTest6(int number) {
7.        this.number = number;
8.     }
9.   
10.  @Parameters
11.  public static Collection<Object[]> data() {
12.     Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
13.     return Arrays.asList(data);
14.  }
15. 
16.  @Test
17.  public void pushTest() {
18.     System.out.println(“Parameterized Number is : ” + number);
19.  }
20.}
It has many limitations here; we have to follow the “JUnit” way to declare the parameter, and the parameter has to pass into constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is “List []”, data has been limited to String or a primitive value for testing.
TestNG
XML file or “@DataProvider” is use to provide vary parameter for testing.
XML file for parameterized test.
 
Only “@Parameters” declares in method which needs parameter for testing, the parametric data will provide in TestNG’s XML configuration files. By doing this, we can reuse a single test case with different data sets and even get different results. In addition, even end user, QA or QE can provide their own data in XML file for testing.
Unit Test
1.  public class TestNGTest6_1_0 {
2.   
3.  @Test
4.  @Parameters(value=”number”)
5.  public void parameterIntTest(int number) {
6.     System.out.println(“Parameterized Number is : ” + number);
7.  }
8.   
9.        }
XML File
1.  <!DOCTYPE suite SYSTEM “http://beust.com/testng/testng-1.0.dtd” >
2.  <suite name=”My test suite”>
3.    <test name=”testing”>
4.   
5.      <parameter name=”number” value=”2″/>
6.   
7.      <classes>
8.         <class name=”com.fsecure.demo.testng.TestNGTest6_0″ />
9.      </classes>
10.  </test>
11.</suite>
@DataProvider for parameterized test.
While pulling data values into an XML file can be quite handy, tests occasionally require complex types, which can’t be represented as a String or a primitive value. TestNG handles this scenario with its @DataProvider annotation, which facilitates the mapping of complex parameter types to a test method.
@DataProvider for Vector, String or Integer as parameter
1.  @Test(dataProvider = “Data-Provider-Function”)
2.    public void parameterIntTest(Class clzz, String[] number) {
3.       System.out.println(“Parameterized Number is : ” + number[0]);
4.       System.out.println(“Parameterized Number is : ” + number[1]);
5.    }
6.   
7.    //This function will provide the patameter data
8.    @DataProvider(name = “Data-Provider-Function”)
9.    public Object[][] parameterIntTestProvider() {
10.         return new Object[][]{
11.                            {Vector.class, new String[] {“java.util.AbstractList”,
12.”java.util.AbstractCollection”}},
13.                            {String.class, new String[] {“1”, “2”}},
14.                            {Integer.class, new String[] {“1”, “2”}}
15.                           };
16.  }
@DataProvider for object as parameter
 
P.S “TestNGTest6_3_0” is an simple object with just get set method for demo.
1.  @Test(dataProvider = “Data-Provider-Function”)
2.  public void parameterIntTest(TestNGTest6_3_0 clzz) {
3.     System.out.println(“Parameterized Number is : ” + clzz.getMsg());
4.     System.out.println(“Parameterized Number is : ” + clzz.getNumber());
5.  }
6.   
7.  //This function will provide the patameter data
8.  @DataProvider(name = “Data-Provider-Function”)
9.  public Object[][] parameterIntTestProvider() {
10. 
11.  TestNGTest6_3_0 obj = new TestNGTest6_3_0();
12.  obj.setMsg(“Hello”);
13.  obj.setNumber(123);
14. 
15.  return new Object[][]{
16.                    {obj}
17.  };
18.}
TestNG’s parameterized test is very user friendly and flexible (either in XML file or inside the class). It can support many complex data type as parameter value and the possibility is unlimited. As example above, we even can pass in our own object (TestNGTest6_3_0) for parameterized test
7. Dependency Test
The “Parameterized Test” means methods are test base on dependency, which will execute before a desired method. If the dependent method fails, then all subsequent tests will be skipped, not marked as failed.
JUnit 4
JUnit framework is focus on test isolation; it did not support this feature at the moment.
TestNG
It use “dependOnMethods “ to implement the dependency testing as following
1.  @Test
2.  public void method1() {
3.     System.out.println(“This is method 1”);
4.  }
5.   
6.  @Test(dependsOnMethods={“method1”})
7.  public void method2() {
8.    System.out.println(“This is method 2”);
9.  }
The “method2()” will execute only if “method1()” is run successfully, else “method2()” will skip the test.
Conclusion
After going thought all the features, i would suggest to use TestNG as core unit test framework for Java project, because TestNG is more advance in parameterize testing, dependency testing and suite testing (Grouping concept). TestNG is meant for high-level testing and complex integration test. Its flexibility is especially useful with large test suites.
Hope this Helps!!!

What is TestNG.xml ?

When you want to run the TestNG test, which you have created, there are two ways to do so.
If you want to run single test case, you can right click on the test, and Run it as TestNG Test. (form Eclipse).
But, if you want to run a set of test cases from various classes, then you need to specify them somewhere, because, you can’t click on each class and run it. Moreover, when running our test cases from the continuous integration tool ( like Jenkins), we need some configuration file which will tell us which test cases to run, if you need to pass some parameters at runtime, then to do that, like wise to achieve something more.
So, In TestNG, all these things are written in a xml file, called as TestNG.xml.
We can configure our test suite utilizing test methods, classes, packages, groups, and so on in single testng.xml file.
TestNG bolster parallel testing, Parameterization (Passing parameters values through XML 
configuration), Data Driven Testing(executing same test strategy numerous times utilizing diverse data) .
The testng.xml file allows lots of flexibility in selecting the test classes and test methods to be executed. You can exclude or include test methods or exclude and include groups.
You can specify the listener to be used by all test classes in the testng.xml file
How to create testing.xml file? 
Create testng suite file manually as below:
  1. Run once your project
  2. Refresh your project
  3. Now, “test-output” folder will get created under your project – unfold the folder
  4. Double click the ‘index.html’ file; it will get open in the Eclipse Browser window
  5. Click on the ‘.xml’ link given on the left panel
  6. The test suite XML will get opened on the right-side panel
  7. Take a copy of the XML content
  8. Right click your project >> New >> File
  9. Give name of your test suite file (with.xml extension e.g. testng.xml) and click finish
  10. Paste the content that you copied from the ‘index.html’ and amend your suite file as per your needs
Sample TestNG.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Aayush Corp Test suite">

<listeners>
<listener class-name="com.aayushCorp.utilities.ITestListenerClass" />
</listeners>

<test verbose="2" name="UserTests" >
<classes>
<class name="com.aayushCorp.appData.tests.UserTests"/>
</classes>
</test> <!-- Default test -->
</suite> <!-- Default suite -->
TestNG.xml is –
•          Controls test runs
•          Optional
•          File can have any name (.xml suffix advised
             TestNG creates “testng-failed.xml”, for easy re-run.
•          Root: <suite> (then <test>/<classes>/<method>)
•          Suite can also point to a list of additional xml suite files.
•          Some of the available specifications are described next.
Hope This helps !!!!
 

How to install TestNG in Eclipse IDE?

TestNG can also be installed in Eclipse by using “Eclipse Marketplace…” Below are the steps:
  1. Open eclipse
  2. Go to Help -> Eclipse Marketplace…
  3. Do search for TestNG (Type the text TestNG in Find text box > Click Go button)
  4. After searching: Click Install button at TestNG for Eclipse area
  5. Follow the further instructions by eclipse
After successful installation: Go to Window -> Preferences. TestNG is enlisted at the left panel in pop-up.
Or 
Click on Help > Install New software
Add the link http://beust.com/eclipse in Work with text box as shown below. 
TestNG feature will be shown, expand the tree node then verify the version.
Tick the check box of TestNG
Click on Next button then Finish button.
I guess you enter wrong software update site. Remove the / and extra spaces around the link “http://beust.com/eclipse/” then try.
Nothing to install outside eclipse.
Thats it.
Hope this Helps !!!

Introduction to TestNG

TestNG is a Testing Framework to group Test Cases, Prioritize Test Cases, Run Test Batches, and Generate Detailed Test Reports.
TestNG is not a Test Tool to conduct Testing operations directly, It won’t recognize Software Objects / Software Elements, but Selenium is used for Testing Operations, and It can recognize Software Objects/Software Elements.
Below image shows that TestNG plays an important role in automation testing.

TestNG is an open source framework where NG means Next Generation.
TestNG is specially designed to cover all types testing categories like Unit, Functional testing, Integration testing, End-to-end etc.
TestNG is a preferred framework of QA analysts as it allows you to generate test reports in both HTML and XML formats.
TestNG enable you to group test cases easily which is not possible in JUnit.
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and testers.
TestNG is an open source framework which is distributed under the Apache software License and is readily available for download.
TestNG is considered to be superior to JUnit because of its advance features Features of TestNG
    Support for Annotations
    Supports parallel testing
    Support for parameterization
    Support for Data Driven Testing using @Dataproviders
    Can include or exclude test methods test execution.
    Setting execution priorities for the test methods
    Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.), Integrated Development Environment (Eclipse).
    Predifindly generates effective Report Generation using ReportNG
I like many things about TestNG.
  1. The methods that use the BeforeClass and AfterClass annotations are not static. Because of this, the WebDriver object does not have to be static either.
  2. The testng.xml file allows lots of flexibility in selecting the test classes and test methods to be executed. You can exclude or include test methods or exclude and include groups.
  3. You can specify the listener to be used by all test classes in the testng.xml file
  4. You can specify how the test scripts can be run in parallel in the testng.xml file
  5. When using parameters, it is possible to have multiple data providers. It is also possible to move a data provider to another class.
  6. It is so easy to re-run only the failed tests
  7. There are default reports in TestNG; the default HTML report can be improved by adding additional information to it; there is also a one file HTML report that is suitable for sending by email.
  8. It is possible to have test scripts dependent on other test scripts or dependent on test groups
  9. You can use soft assertions for grouping multiple normal assertions together; everything included in a soft assertion is executed even if some of assertions fail
  10. Page Factories

 

 Hope this helps !!!!

What is ITestContext in testng? (Selenium). How to use ITestContext in Selenium?

Sharing data across Tests in different TestClasses – 

ITestContext is basically used to store and share data across the tests in selenium by using TestNG framework.
Let us consider below scenario –
We have 10 test cases (@Test methods) to be executed to complete one end to end test case. Now in call 10 test cases (@Test methods) we are sharing some data like “Customer_id”, which should be unique and same in our end to end test case i.e. in our 10 @Test methods. During the execution of end to end test case, it should be same.
To handle this scenario, we have two ways – 
            1.      If all 10 @Test methods are in same class, then we can store “Customer_id”  in a class level variable (instance variable)  and share it. But it may require high maintenance.
          
            2.      Another way to handle this is, ITestContext
Let us see How ITestContext works.
In any @Test method, we can use “iTestContext” by passing it as a parameter to the method.  Syntax as below – 

 @Test
public void test1a(ITestContext context){

}
Here, we can set the value that we want to share  in ITestContex, as below –
 @Test
public void test1a(ITestContext context){

String Customer_id = "C11012034";
context.setAttribute("CustID", Customer_id);
}
Now, we can get this value, which is stored in ITestContext variable with other tests, as below –

  String Customer_id1 = (String) context.getAttribute("CustID");
Below piece of code can help you to understand how ITestContext works.

package iTestContextLearn;

import org.testng.ITestContext;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Test1 {

@BeforeTest
public void SetData(ITestContext context){

String Customer_id = "C11012034";
context.setAttribute("CustID", Customer_id);
System.out.println("Value is stored in ITestContext");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");

}
@Test
public void Test1a(ITestContext context){
String Customer_id1 = (String) context.getAttribute("CustID");
System.out.println("In Test1, Value stored in context is: "+Customer_id1);
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");

}
@Test
public void Test2a(ITestContext context){
String Customer_id1 = (String) context.getAttribute("CustID");
System.out.println("In Test2, Value stored in context is: "+Customer_id1);
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");

}
}
Note: All the @Test methods that we are going to run must be in one class only. We will be calling methods from different other classes. We can share the data with methods of different classes.
Hope this helps !!!! Post your comments / questions 

Headless testing in selenium WebDriver using HtmlUnitDriver

What is headless testing?
Headless testing is nothing but the testing which is carried out with the help of headless browsers.

What is headless browser?
We can guess it form the name, Headless – do not have a head, this means, during testing, we cannot see browser running but it will run internally.
Headless browser is a browser without GUI. So, the browser accesses the webpages internally and perform actions on them, but user cannot see that.
Some if the examples of headless drivers include – 
HtmlUnit
Ghost
PhantomJS
ZombieJS
We will talk about HtmlUnitDriverhere.
HtmlUnitDriver is a faster an most light weight version of implementation of WebDriver.
By using HtmlUnitDriver, we can select the browser (Chrome / IE/ firefox) versions. This means we can emulate HtmlUnitDriver to other browsers.
HtmlUnitDriver is platform independent.
Advantages of headless testing – 
Headless browser is faster because no GUI appear during testing.
We can use this in a situation where you have to prepare test data, or you have to pass contents from one page to another page simply.
Let us look at the example, how can we use HtmlUnitDriver for headless testing?

package samplePackage;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class HtmlUnitDriverClass {

public static void main(String[] args) {

//initialize HtmlUnitDriver wit variable driver.

WebDriver driver = new HtmlUnitDriver();

driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in");

System.out.println("Title of the page is: "+driver.getTitle());


}

}
Console Output: 
Title of the page is: About Software Testing . . .
When the above lines of code executes, no browser has been launched, but you can see, correct title of the page is been printed. what this mean is, browser has launched internally.

Testing different browsers on HtmlUnitDriver (headless testing)
We can test various browsers on HtmlUnitDriver for headless testing. Let us see  as below –
Select Mozilla Firefox  – 
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.FIREFOX_38);
Select Chrome browser –
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.CHROME);
Select IE browser – 
                                HtmlUnitDriver driver = newHtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_11);
Hope this helps !!!!