Top 21 Selenium TestNG Framework Interview Questions and Answers


TestNG is a popular testing framework for Java applications that enables developers to write automated tests for their code. It provides a rich set of features and annotations that help testers create efficient and comprehensive test suites. 

If you are preparing for a TestNG interview, you may be asked a wide range of questions related to the framework. In this blog post, we will cover some of the most commonly asked TestNG interview questions along with their answers and coding examples.

  1. What is TestNG and what are its advantages?

Answer: TestNG is a testing framework for Java that is designed to cover all categories of tests: unit, functional, end-to-end, integration, and more. TestNG offers several advantages over other testing frameworks, including:
  • Flexible test configuration: TestNG allows testers to configure tests using XML files or Java code. This flexibility makes it easier to customize tests and run them in different environments.
  • Annotations-based testing: TestNG uses annotations to define tests, which makes it easier to write and read test code.
  • Easy test grouping: TestNG supports test grouping, which allows testers to run tests in parallel, group them by priority or category, and more.
  • Built-in test reports: TestNG generates HTML reports that show the results of tests, including test logs, errors, and exceptions.

  1. What are the annotations in TestNG?

Answer: TestNG provides several annotations that testers can use to define tests. Some of the most commonly used annotations include:
  • @Test: This annotation identifies a method as a TestNG test method.
  • @BeforeSuite: This annotation is used to run a method before the test suite starts.
  • @AfterSuite: This annotation is used to run a method after the test suite finishes.
  • @BeforeTest: This annotation is used to run a method before each test method in a test file.
  • @AfterTest: This annotation is used to run a method after each test method in a test file.
  • @BeforeClass: This annotation is used to run a method before the first test method in a test class.
  • @AfterClass: This annotation is used to run a method after the last test method in a test class.
  • @BeforeMethod: This annotation is used to run a method before each test method.
  • @AfterMethod: This annotation is used to run a method after each test method.
  • @DataProvider: This annotation is used to specify a data provider method for a test method.
  • @Parameters: This annotation is used to specify parameters for a test method.

  1. How do you create a TestNG test file?

Answer: To create a TestNG test file, you need to create a Java class and add the necessary annotations and methods. Here's an example:

typescript
import org.testng.annotations.Test
public class MyTest
@Test 
public void testMethod() { 
// Test code here 
 } }

In this example, the class is named MyTest and contains a test method annotated with @Test. You can run this test file using TestNG by creating an XML file that specifies the test classes to run.


  1. How do you run a TestNG test file?

Answer: To run a TestNG test file, you can use the TestNG command line or a build tool such as Maven or Gradle. Here's an example of how to run a test file using the TestNG command line:

bash
java -cp "path/to/testng.jar:path/to/test-classes/" org.testng.TestNG testng.xml

In this example, "path/to/testng.jar" and "path/to/test-classes/" should be replaced with the actual paths to the TestNG JAR file and the test classes, respectively. "testng.xml" is the name of the XML file that specifies the test classes to run. You can also run tests from within an IDE such as Eclipse or IntelliJ IDEA.


  1. What is priority in TestNG tests?

Answer: TestNG provides several ways to prioritize tests. One way is to use the priority attribute in the @Test annotation. Test methods with a lower priority value are executed before methods with a higher priority value. For example:

less
import org.testng.annotations.Test
public class MyTest
@Test(priority = 1
public void testMethod1() { // Test code here
@Test(priority = 2
 public void testMethod2() { // Test code here } }

In this example, testMethod1 is executed before testMethod2 because it has a lower priority value. You can also use the dependsOnMethods attribute to specify that one test method depends on another. For example:

less
import org.testng.annotations.Test
public class MyTest
 @Test 
 public void testMethod1() { 
// Test code here 
 } 
 @Test(dependsOnMethods = "testMethod1"
 public void testMethod2() { 
// Test code here 
 } 
}

In this example, testMethod2 is executed after testMethod1 because it depends on it.


  1. How do you use TestNG data providers?

Answer: TestNG data providers allow testers to pass data to test methods from external sources such as CSV files, Excel spreadsheets, or databases. To use a data provider, you need to define a method that returns a two-dimensional object array and annotates it with @DataProvider. For example:

typescript
import org.testng.annotations.Test
import org.testng.annotations.DataProvider
public class MyTest
@Test(dataProvider = "data-provider"
public void testMethod(String data) { // Test code here
@DataProvider(name = "data-provider"
public Object[][] dataProviderMethod() { 
return new Object[][] { { "data1" }, { "data2" }, { "data3" } }; 
 } 
}

In this example, the dataProviderMethod() method returns a two-dimensional object array that contains the data to pass to the testMethod() method. The testMethod() method takes a String parameter that represents the data passed from the data provider.


  1. How do you use TestNG listeners?

Answer: TestNG listeners are used to customize the behavior of TestNG tests. You can use listeners to perform actions before or after a test method, before or after a test suite, before or after a test class, and more. To use a listener, you need to implement the corresponding interface and add it to the testng.xml file or annotate it directly on a test class. For example:

java
import org.testng.annotations.Listeners; 
import org.testng.annotations.Test; 
@Listeners(MyTestListener.class) 
public class MyTest
@Test 
public void testMethod()
// Test code here 
 } }

In this example, the @Listeners annotation is used to specify the MyTestListener class as a listener for the MyTest class. The MyTestListener class implements one or more TestNG listener interfaces.


  1. How do you configure TestNG to run tests in parallel?

Answer: TestNG supports running tests in parallel to speed up test execution. To run tests in parallel, you need to specify the parallel attribute in the testng.xml file or in the @Test annotation. For example:

php
<suite name="My Suite" parallel="tests"> <test name="My Test"> <classes> <class name="MyTest1" /> <class name="MyTest

In this example, the parallel attribute is set to "tests", which means that each <test> element in the suite is run in a separate thread. You can also set the parallel attribute to "classes", "methods", or "instances" to specify different levels of parallelism.


  1. How do you use TestNG to perform data-driven testing?

Answer: TestNG provides several ways to perform data-driven testing. One way is to use data providers, as mentioned earlier. Another way is to use the @Factory annotation to create a new instance of a test class for each set of test data. For example:

typescript
import org.testng.annotations.Factory
public class MyTestFactory
@Factory 
public Object[] createTests() { 
Object[] tests = new Object[3]; 
tests[0] = new MyTest("data1"); 
 tests[1] = new MyTest("data2"); 
 tests[2] = new MyTest("data3"); 
return tests; 
 } }

In this example, the createTests() method returns an array of MyTest instances, one for each set of test data. Each instance is created with a different set of data passed to its constructor.


  1. How do you use TestNG to perform cross-browser testing?

Answer: TestNG can be used to perform cross-browser testing by using Selenium WebDriver to interact with the web browser. To test multiple browsers, you can use a data provider to pass the browser type as a parameter to the test method. For example:

typescript
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.firefox.FirefoxDriver
import org.testng.annotations.*; 
public class MyTest
private WebDriver driver; 
@BeforeMethod @Parameters("browser"
public void setup(String browser) { 
if(browser.equalsIgnoreCase("chrome")) { 
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); 
 driver = new ChromeDriver(); } 
else if(browser.equalsIgnoreCase("firefox")) { 
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver"); 
 driver = new FirefoxDriver(); } 
 } 
@Test 
public void testMethod() { 
// Test code here 
 }
@AfterMethod 
public void teardown() { 
 driver.quit(); 
 } 
@DataProvider(name = "browsers"
public Object[] dataProviderMethod() { 
return new Object[] { "chrome", "firefox" }; 
 } 
}

In this example, the setup() method is annotated with @BeforeMethod and takes a String parameter named "browser". The @Parameters annotation is used to indicate that the parameter value is passed from the testng.xml file. The dataProviderMethod() method returns an array of browser types to be passed to the test method using the @Test annotation. The teardown() method is annotated with @AfterMethod and is used to close the browser after the test method completes.


  1. How do you use TestNG to perform API testing?

Answer: TestNG can be used to perform API testing by using libraries such as RestAssured or HttpClient to make API requests and assertions. Here's an example:

java
import org.testng.annotations.*; 
import io.restassured.RestAssured; 
import io.restassured.response.Response; 
import static io.restassured.RestAssured.*; 
public class MyAPITest
@BeforeClass 
public void setup()
RestAssured.baseURI = "https://jsonplaceholder.typicode.com"
 } 
@Test 
public void testGetPosts()
Response response = given() .when() .get("/posts") .then() .extract().response(); 
int statusCode = response.getStatusCode(); 
Assert.assertEquals(statusCode, 200); 
String responseBody = response.getBody().asString(); Assert.assertTrue(responseBody.contains("userId")); } 
@Test 
public void testPostNewUser()
String requestBody = "{ \"name\": \"John Doe\", \"username\": \"johndoe\", \"email\": \"[email protected]\" }"
Response response = given() 
 .body(requestBody) 
 .when() 
 .post("/users"
 .then() 
 .extract()
.response(); 
int statusCode = response.getStatusCode(); 
Assert.assertEquals(statusCode, 201); 
 } }

In this example, the setup() method is annotated with @BeforeClass and sets the base URI for the API requests. The testGetPosts() method sends a GET request to the /posts endpoint and asserts that the response status code is 200 and that the response body contains the "userId" field. The testPostNewUser() method sends a POST request to the /users endpoint with a JSON request body and asserts that the response status code is 201.


  1. How do you use TestNG to test RESTful web services?

Answer: TestNG can be used to test RESTful web services by making HTTP requests and assertions using libraries such as RestAssured or HttpClient. Here's an example:

java
import org.testng.annotations.*; 
import io.restassured.RestAssured; 
import io.restassured.response.Response; 
import static io.restassured.RestAssured.*; 
public class MyWebServiceTest
@BeforeClass 
public void setup()
 RestAssured.baseURI = "https://api.openweathermap.org"
 RestAssured.basePath = "/data/2.5/weather"
 RestAssured.queryParam("appid", "your_app_id_here"); } 
@Test 
public void testGetWeatherByCityName()
Response response = given() .queryParam("q", "London").when().get().then() .extract().response(); 
int statusCode = response.getStatusCode(); 
 Assert.assertEquals(statusCode, 200); 
String responseBody = response.getBody().asString(); Assert.assertTrue(responseBody.contains("weather")); 
 } 
@Test 
public void testGetWeatherByZipCode()
Response response = given() .queryParam("zip", "90210,us").when().get() .then().extract().response(); 
int statusCode = response.getStatusCode(); 
Assert.assertEquals(statusCode, 200); 
String responseBody = response.getBody().asString(); Assert.assertTrue(responseBody.contains("main")); 
} }

In this example, the setup() method is annotated with @BeforeClass and sets the base URI, base path, and query parameters for the API requests. The testGetWeatherByCityName() method sends a GET request to the API endpoint with a query parameter for the city name and asserts that the response status code is 200 and that the response body contains the "weather" field. The testGetWeatherByZipCode() method sends a GET request to the same API endpoint with a query parameter for the zip code and country code and asserts that the response status code is 200 and that the response body contains the "main" field.


  1. What is the difference between a test method and a configuration method in TestNG?

Answer: In TestNG, a test method is a method that contains the actual test logic, while a configuration method is a method that is used to set up or tear down the test environment. Configuration methods include:
  • @BeforeSuite
  • @AfterSuite
  • @BeforeTest
  • @AfterTest
  • @BeforeGroups
  • @AfterGroups
  • @BeforeClass
  • @AfterClass
  • @BeforeMethod
  • @AfterMethod

Test methods are annotated with @Test, while configuration methods are annotated with the corresponding annotation from the list above.

Here's an example:

less
import org.testng.annotations.*; 
public class MyTest
@BeforeSuite 
 public void beforeSuite() { 
// set up before all tests in the suite
@BeforeTest 
public void beforeTest() { 
// set up before all tests in the current test tag
@BeforeClass 
 public void beforeClass() { 
// set up before all test methods in the current class
@BeforeMethod public void beforeMethod() { 
// set up before each test method
@Test 
 public void testMethod1() { 
// test logic here
@Test 
 public void testMethod2() { 
// test logic here
@AfterMethod public void afterMethod() { 
// tear down after each test method
@AfterClass public void afterClass() { 
// tear down after all test methods in the current class
@AfterTest public void afterTest() { 
// tear down after all tests in the current test tag
@AfterSuite public void afterSuite() { 
// tear down after all tests in the suite 
 } }

In this example, the configuration methods are used to set up and tear down the test environment, while the test methods contain the actual test logic.


  1. What is the use of the @DataProvider annotation in TestNG? Give an example.

Answer: The @DataProvider annotation is used to provide data to a test method in TestNG. The method annotated with @DataProvider must return a two-dimensional array of objects, where each row represents a set of test data and each column represents a parameter value.

Here's an example:

typescript
import org.testng.annotations.*; 
public class MyTest { @DataProvider(name = "testData"
public Object[][] testData() { 
return new Object[][] { { "John", "Doe", 25 }, { "Jane", "Smith", 30 }, { "Bob", "Johnson", 40 } }; } 
@Test(dataProvider = "testData"
public void testMethod(String firstName, String lastName, int age) { System.out.println("Name: " + firstName + " " + lastName); System.out.println("Age: " + age); 
 } }

In this example, the testData() method is annotated with @DataProvider and returns a two-dimensional array of objects that contains test data for the testMethod() method. The testMethod() method is annotated with @Test and has three parameters that correspond to the columns in the test data array. The testMethod() method will be called three times, once for each row in the test data array, with the parameter values set to the corresponding values in the current row.


  1. What is the difference between a soft assert and a hard assert in TestNG?

Answer: In TestNG, a hard assert will stop the test execution immediately if the assertion fails, while a soft assert will not. Instead, a soft assert will continue executing the test, and at the end of the test, a summary of all the soft assert failures will be displayed.

Here's an example:

java
import org.testng.asserts.*; 
public class MyTest
private final SoftAssert softAssert = new SoftAssert(); 
@Test 
public void testMethod()
int a = 10; int b = 5
softAssert.assertTrue(a > b, "a is not greater than b"); softAssert.assertEquals(a, b * 2, "a is not equal to b * 2"); softAssert.assertAll(); 
 } }

In this example, the testMethod() method contains two soft asserts, one that checks if a is greater than b and one that checks if a is equal to b * 2. The assertAll() method is called at the end of the test to summarize all the soft assert failures.

If the first soft assert fails, the test will continue executing, and the second soft assert will be checked. At the end of the test, a summary of the failed soft asserts will be displayed.

If the first assert were a hard assert, and it failed, the test would stop immediately, and the second assert would not be checked.


  1. What is the difference between a factory and a data provider in TestNG?

Answer: A factory in TestNG is used to create multiple instances of a test class, each with different data. A data provider is used to provide data to a single test method.

Here's an example of using a factory:

typescript
import org.testng.annotations.*; 
public class MyTest
@Factory 
public Object[] createInstances() { 
Object[] result = new Object[3]; 
 result[0] = new MyClass("data1"); 
 result[1] = new MyClass("data2"); 
 result[2] = new MyClass("data3"); 
return result; } } 

class MyClass
private final String data; 
public MyClass(String data) { 
this.data = data; 
 } 
@Test 
public void testMethod() { 
System.out.println("Data: " + data); 
 } }

In this example, the createInstances() method is annotated with @Factory and returns an array of MyClass instances with different data. The testMethod() method in MyClass is annotated with @Test and will be called once for each MyClass instance.

Here's an example of using a data provider:

typescript
import org.testng.annotations.*; 
public class MyTest
@DataProvider(name = "testData"
public Object[][] testData() { 
return new Object[][] { { 1, 2, 3 }, { 4, 5, 9 }, { 7, 8, 15 } }; 
 } 
@Test(dataProvider = "testData"
public void testMethod(int a, int b, int expected) { 
 int actual = a + b; 
Assert.assertEquals(actual, expected, "actual sum is not equal to expected sum"); 
 } }

In this example, the testData() method is annotated with @DataProvider and returns a two-dimensional array of integers. The testMethod() method is annotated with @Test and has three parameters that correspond to the columns in the test data array. The testMethod() method will be called three times, once for each row in the test data array, with the parameter values set to the corresponding values in the current row.


  1. How can you run tests in parallel in TestNG?

Answer: TestNG provides a built-in mechanism for running tests in parallel, which can significantly reduce the overall test execution time. To run tests in parallel, you can use the parallel attribute in the suite tag in your testng.xml file.

Here's an example:

php
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > 
<suite name="My Suite" parallel="tests" thread-count="2"> 
<test name="Test 1"> 
<classes> <class name="com.example.MyTestClass1" /> </classes> 
</test> 
<test name="Test 2"> 
<classes> <class name="com.example.MyTestClass2" /> </classes> 
</test> 
</suite>

In this example, the suite tag has the parallel attribute set to "tests" and the thread-count attribute set to "2". This means that TestNG will run the tests in Test 1 and Test 2 in separate threads, with a maximum of two threads running at the same time.

Alternatively, you can use the @Test annotation's threadPoolSize attribute to specify the number of threads that should be used to run a particular test method. For example:

java
@Test(threadPoolSize = 3) 
public void testMethod()
// ... }

In this example, the testMethod() method will be run in three parallel threads.


  1. How can you ignore a test in TestNG?

Answer: To ignore a test in TestNG, you can use the @Test annotation's enabled attribute and set it to false. For example:

typescript
@Test(enabled = false
public void ignoredTestMethod() { 
// ... }

In this example, the ignoredTestMethod() method will not be run during test execution.

Alternatively, you can use the @Test annotation's dependsOnGroups attribute to specify that a test should be skipped if a certain group of tests fails. For example:

less
@Test(groups = "sanity"
public void sanityTestMethod() { 
// ...
@Test(dependsOnGroups = "sanity"
public void dependentTestMethod() {
// ... }

In this example, the dependentTestMethod() method will only be run if the sanityTestMethod() method passes. If the sanityTestMethod() method fails, the dependentTestMethod() method will be skipped.


  1. How can you set a time limit for a test in TestNG?

Answer: To set a time limit for a test in TestNG, you can use the @Test annotation's timeOut attribute and specify the time limit in milliseconds. For example:
java
@Test(timeOut = 1000) 
public void timedTestMethod()
// ... }

In this example, the timedTestMethod() method will be aborted if it takes longer than 1000 milliseconds (i.e., one second) to complete.


  1. How can you group tests in TestNG?

Answer: To group tests in TestNG, you can use the @Test annotation's groups attribute and specify a group name. For example:

less
@Test(groups = "sanity"
public void sanityTestMethod() { 
// ...
@Test(groups = "regression"
public void regressionTestMethod() { 
// ... }

In this example, the sanityTestMethod() method is in the "sanity" group, and the regressionTestMethod() method is in the "regression" group.

You can then specify which groups of tests you want to run in your testng.xml file by using the include and exclude attributes of the run tag. For example:

php
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="My Suite">
  <run>
    <include name="sanity" />
    <exclude name="regression" />
  </run>
  <test name="My Test">
    <classes>
      <class name="com.example.MyTestClass" />
    </classes>
  </test>
</suite>
```

In this example, the run tag has the include attribute set to "sanity" and the exclude attribute set to "regression". This means that only tests in the "sanity" group will be run, and tests in the "regression" group will be excluded.


  1. How can you specify the order in which tests are run in TestNG?

Answer: To specify the order in which tests are run in TestNG, you can use the @Test annotation's priority attribute and specify a priority value. Tests with lower priority values will be run first.

Here's an example:

less
@Test(priority = 1
public void highPriorityTestMethod() { 
// ... 
@Test(priority = 2
public void mediumPriorityTestMethod() { 
// ... 
@Test(priority = 3
public void lowPriorityTestMethod() { 
// ... }

In this example, the highPriorityTestMethod() method will be run first, followed by the mediumPriorityTestMethod() method, and then the lowPriorityTestMethod() method.