Top 35+ Most Popular TestNG Interview Questions and Answers

Table of Contents

Most Popular TestNG Interview Questions

In this post we will cover TestNG Interview Questions with Answers. Our main focus to prepare Selenium Interview Questions too. I am sure these questions will be helpful to crack the TestNG Interview successfully.

Below listed questions frequently asked in Interviews.

What is TestNG?

TestNG is a testing framework which is inspired from JUnit and NUnit and also reduced the limitations of JUnit and NUnit that make more powerful and easier to use.
It is an open source automation testing framework. Most of the Selenium users use testng because of many features of TestNG.

What are the advantages of TestNG over Junit?

1.Annotations makes easy to use selenium.
2.Generated logs
3.Generate reports
4.Test cases can be grouped & Prioritized.
5.Parallel testing is possible.
6.Support for data-driven Testing.
7.Support different third party tool like Eclipse, Maven etc.

TestNG Interview Question TestNG Features Annotations Grouping Assertions
                                                                                Features of TestNG

How to integrate TestNG with Eclipse?

  1. Click on Help –> Install New Software
  2. Add the link http://beust.com/eclipse in Work with text box as shown below:
  3. Check the checkbox of TestNG.
  4. Click on Next and accept the terms of the license agreement.
  5. Click on finish.
  6. Restart the eclipse.

What are the Annotations Present in TestNG?

@BeforeSuite

 @AfterSuite

 @BeforeClass

 @AfterClass

 @BeforeTest

 @AfterTest

 @BeforeGroups

 @AfterGroups

 @BeforeMethod

 @AfterMethod

 @DataProvider

 @Factory

 @Listeners

 @Parameters

 @Test


Testng interview questions for 2 years experience

What is the Execution Order of Annotations?

  BeforeSuite

  BeforeTest

  BeforeClass

  BeforeMethod

  Test

  AfterMethod

  AfterClass

  AfterTest

  AfterSuite

TestNG Interview Questions TestNG Annotations
                                                                                      TestNG Annotations

What is the difference between before test and before class?

        @BeforeClass : The annotated method will run before the first test method in the current class is invoked.

        @BeforeTest : The annotated method will run before any test method belonging to the classes inside the <test> tag is run.

What is the difference between before method and before test in testng?

        @BeforeMethod:-This annotated method will run before each test method.

         @BeforeTest:-This annotated method will run before any test method belonging to the classes inside the <test> tag is run.

What are the different assertions in TestNG?

Assertions are used to validate the tests in TestNG.

There are different assertions which are mentioned below.

assertEquals – Passes if arguments are equal otherwise fails.

assertNotEquals – If actual and expected values match then it is failed.

assertTrue – Passes if the input condition is true otherwise fails.

assertFalse – Passes if the input condition is false otherwise fails.

https://www.youtube.com/watch?v=dvUPSnGQZCM&ab_channel=Mukeshotwani

What is Data Provider in TestNG?

 Data provider is used for parameterization in TestNG. It uses @DataProvider annotation and two dimensional array Object[][].

How to Execute failed test cases in TestNG?

Steps to follow:-

1.    After first run of an automated test run. Right click on Project folder – Click on Refresh

2.    A folder will be generated named “test-output” folder. Inside “test-output” , you can find “testng-failed.xml”

3.    Run “testng-failed.xml” to execute the failed test cases again.


[TestNG interview questions for experienced professionals]

 

I have a package which has 10 class files, would like to run first 7 class files in parallel and rest 3 in sequential how do you that?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Complete test suite">
        <test name="Parallel tests" parallel="methods" thread-count="4">
        <groups>
            <run>
              <exclude name="sequential-test"></exclude>
            </run>
        </groups>
        <classes>
            <class name="packagename.classname" />
            <class name="packagename.classname" />
            <class name="packagename.classname" />
        </classes>
    </test>
    <test name="Sequential tests" parallel="false" >
        <groups>
            <run>
                <include name="sequential-test"></include>
            </run>
        </groups>
        <classes>
            <class name="packagename.classname" />
            <class name="packagename.classname" />
            <class name="packagename.classname" />
        </classes>
    </test>
</suite>

As you can see, I have two types of tests, tests which can be run in parallel and others that should be run in sequential. In First <test> tag, we have set parallel attribute value as a methods so it run parallel way and also we have set exclude sequential test using exclude attribute.

In second <test> tag we have used include attribute to run test in sequential manner as per our requirements.

How to create testng.xml file in eclipse?

Follow below steps to generate the testng.xml file in eclipse.

  1. Right click on your eclipse project
  2. Mouse hover on TestNG option.
  3. Click on Convert to TestNG.
  4. Click on Next button.
  5. Click on Finish button.

Why we need testng.xml file in our Automation?

When we test a project in Selenium then there are a lot of classes created on it. If we want to run those classes for automation then we cannot do this at once. Hence we need to create test suite so that all the classes can run at once.

This can be achieving by using testng.xml file.

What is Paramerization is TestNG?

In TestNG, Using Parameterization we can run one test method multiple times with different set of data. This process also known as data-driven testing.

There are two ways to achieve parameterization.

  • Using testng.xml
  • Using DataProviders annotation.

How to pass parameters from testng.xml to the 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, ParameterTest.java and add a test method say parameterTest() to the test class. This method takes a string as input parameter. Add the annotation @Parameters(“browser”) to this method.

public class ParameterizedTest {
    @Test
    @Parameters("browser")
    public void parameterizedTest(String browser){
        if(browser.equals("FF")){
            System.out.println("Open Firefox Driver");
        }else if(browser.equals("CH")){
            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="FF"/>

 

How do you handle dependency tests case in TestNG?

TestNG provides attributes dependsOnMethods in @Test annotations to handle it.

Example:

package blogPkg;

import org.testng.annotations.Test;

public class DependsOnMethods {

            public class Dependent {

            }

            @Test(dependsOnMethods = { "OpenBrowser" })

            public void SignIn() {
                        System.out.println("This will execute second (SignIn)");
            }

            @Test
            public void OpenBrowser() {

                        System.out.println("This will execute first (Open Browser)");
            }

            @Test(dependsOnMethods = { "SignIn" })

            public void LogOut() {

                        System.out.println("This will execute third (Log Out)");

       }

}



Explain Grouping in TestNG?

TestNG allows us to run test cases in grouping, It means using groups multiple test cases execution is possible. So this is provide flexibility to divide the test cases and run it.

For example if we have two sets of test cases, one is for Regression testing and second is for Smoke testing so we can divide it by using groups and run both types of testing back to back.

This will execute the current suit first and then it will execute the included list of suites one by one.

Can we run multiple test suites in TestNG?

Yes

<suite name="allSuites">
  <suite-files>
    <suite-file path="suite1.xml" />
    <suite-file path="suite2.xml" />
  </suite-files>
  </suite>

It will execute the current suit first and then it will execute the included list of suites one by one.

What is Hard and Soft Assert in TestNG?

  •  Hard Assert – Hard Assert throws an AssertExceptionimmediately when an assert statement fails and test suite continues with next method.

disadvantage is It marks method as fail if assert condition gets failed and the remaining statements inside the method will be aborted.

To prevent this, we need to use Soft Assert. Let’s see what is Soft Assert?

  •  Soft Assert – Soft Assert collects errors during @Test method. This assertion does not throw an exception when an assert fails and would continue with the next step after the assert statement. If there is any exception and want to throw it then need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.

 

How to ignore  test cases in TestNG?

The annotation @Test(enabled = false) helps to disable this test case.

What is alwaysRun attribute in TestNG?

If we want to run a test method always even it is dependent on any other test case and dependent test method is failed or skipped.

If we set true then this method will run always.

Syntax:

/ alwaysRun attribute will override dependsOnMethods if dependent method is failed or skipped
   @Test(dependsOnMethods = "method1", alwaysRun=true)
   public void method2() 
   {
      System.out.println("Method 2");
   }

 

How to skip test cases in test-NG(Class level and Method level)?

By using exclude name in testing.xml we can skip test method in any class. Below format of testing.xml.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Sample Test Suite" verbose="1" >
  <test name="Method Test Cases" >
    <classes>
       <class name="com.easy.entry.AddTestCase"/>
        <methods>
        <include name="addLocationTestCase" />
        <include name="addDepartmentTestCase" />
        <exclude name="addEmployeeTestCase" />
      </methods>
    </classes>
  </test>
</suite>

What is use of listeners annotation in TestNG?

 TestNG Listener is an interface that modify default behavior of TestNG. It allows customizing TestNG reports and logs.

Types of Listeners in TestNG:-

There are so many listeners which allow you to change the TestNG’s behavior.

Below are the few TestNG listeners:

  1. IAnnotationTransformer
  2. IAnnotationTransformer2
  3. IConfigurable
  4. IConfigurationListener
  5. IExecutionListener
  6. IHookable
  7. IInvokedMethodListener
  8. IInvokedMethodListener2
  9. IMethodInterceptor
  10. IReporter
  11. ISuiteListener
  12. ITestListener

 

What is the use of alwaysRun attributes in testing?

If set to true, this test method will always be run even if it depends on a method that failed.

What does @Test(invocationCount= ) and @Test(threadPoolSize)  indicates?

@Test(threadPoolSize=?) : This attributes is use to run the test method through multiple threads.

@Test(invocationCount=)  : This attributestells TestNG, how many times this test method should run.

 

Can we run a testng test without testng.xml file?

Yes, we can run. From command-line using ant or maven.

 

How to control test execution order in TestNG?

We can set “preserve-order” attributes to true in the TestNG.xml.

<test name="TestOrder" preserve-order="true">
    <classes>
        <class name="TestNGOrderOne">
            <methods>
                <include name="stepOne" />
                <include name="stepTwo" />
            </methods>
        </class>
    </classes>
</test>

What happen when test priority is set zero?

By default, each test case in testNG gets zero priority.

Zero priority test case will execute always first.

 

What are the methods present in ITestListener interface? [Imp. for TestNG Interview Questions]

There are different methods available in ITestListener.

onStart() – This method is called before any test method execution.

onTestSuccess() –  This method is called when any test method successfully run.

onTestfailure() – This method iscalled whenany test method is failed.

onTestSkipped() – This method is called on any skipped method.

onFinish() – This method is called when all the test method gets executed.

ITestListener in TestNG
TestNG Listener

How to use groups attributes at class level?

In most of the cases test scenario falls into same group, then no need to go in each test and use groups attribute. We can use groups attributes at class level inside @Test annotation.

See below example. We defined groups attributes at class level so it will be apply on all test methods which are in this class.

package com.automationtestings.test;
import org.testng.annotations.Test;

@Test(groups="scenario1")
public class Epic
{
    @Test
    public void funcTest1() {
        System.out.println("test1");
    }
@Test
    public void funcTest2() {
        System.out.println("test2");
    }

    @Test(groups="scenario2")
    public void funcTest3() {
        System.out.println("test3");
    }
}

How to run a single TestNG test method using maven?

Using below maven command we can run it.

mvn -Dtest=<Test Class>#<Test Method> test

How to run a set of TestNG groups method using maven?

If we have many testNG groups e.g. scenario1, scenario2, scenario3 then we can run it using single command.

mvn test -Dgroups=scenario1,scenario2,scenario3

What is @Factory annotation and how to use this?

@Factory annotation is use to defined a method as a factory for providing a set of objects to use by TestNG test classes. @factory is always returned an array of object class.

TestNG @Factory annotation is useful when we want to run multiple test classes using single test class.

package com.automationtestings.utils;
import org.testng.annotations.Test;
public class Test1 {
	@Test
	public void test1() {
		System.out.println("Test1 method");
	}
}

package com.automationtestings.utils;

import org.testng.annotations.Test;

public class Test2 {

	@Test
	public void test2() {
		System.out.println("Test2 method");
	}
}

Now we can use Factory method that returns the Object array of above classes.

import org.testng.annotations.Factory;

public class TestNGFactory1 {

	@Factory()
	public Object[] getTestClasses() {
		Object[] tests = new Object[2];
		tests[0] = new Test1();
		tests[1] = new Test2();
		return tests;
	}
	
}

Output:

[RemoteTestNG] detected TestNG version 6.14.6

Test1 test method

Test2 test method

PASSED: test1

PASSED: test2

===============================================

    Default test

    Tests run: 2, Failures: 0, Skips: 0

===============================================

Default suite

Total tests run: 2, Failures: 0, Skips: 0

Why reporter class used in TestNG?

Reporter class- logs the messages into TestNG methods test execution. These messages give the status, information or any other details about the test execution.

How to run multiple TestNG tests in parallel way? [Imp. for TestNG Interview Questions]

We can run the multiple TestNG tests in parallel. In testng.xml file, there is a suite tag which has a parallel attributes.

We can run the tests in parallel at different level i.e. Tests, Classes, methods and instances level.

Summary

Hope this Q&A tutorial was covered all important TestNG Interview Questions that will helpful to clear your Selenium automation interviews for automation testers.

In future I will add more real time interview questions and also will add TestNG interview questions.

Final words, Bookmark this post TestNG Interview Questions for your future reference.

If you have other questions or feedback, the comment section is yours. Don’t forget to leave a comment below!

 

Don’t miss the following Posts:

Selenium Interview Questions and Answers

Web Services Interview Questions and Answers

 

Leave a Comment