Top 50 TestNG Interview Questions and Answers (2026)

Top TestNG Interview Questions and Answers

Preparing for a TestNG interview? It is time to consider the questions that showcase your strengths. A solid TestNG interview foundation reveals depth, confidence, and readiness valued by hiring teams.

Opportunities in this domain span automation growth, evolving frameworks, and practical testing applications requiring technical and professional experience. Working in the field demands domain expertise, analysis skills, and a flexible skillset that helps freshers, mid-level, and senior professionals crack common top questions and answers across technical, basic, and advanced.
Read more…

๐Ÿ‘‰ Free PDF Download: TestNG Interview Questions & Answers

Top TestNG Interview Questions and Answers

1) What is TestNG and why is it used in automation testing?

TestNG (Test Next Generation) is a testing framework inspired by JUnit and NUnit but enhanced with advanced capabilities such as grouping, sequencing, parameterization, and dependency management. It is primarily used in automation testing to streamline test execution, improve test organization, and generate detailed HTML and XML reports.

Key benefits of TestNG include:

  • Supports parallel test execution, reducing total run time.
  • Provides annotations that control the test flow effectively.
  • Offers data-driven testing through the @DataProvider annotation.
  • Generates customizable reports for better debugging.

For example, TestNG allows you to execute smoke, regression, and integration test groups independently without modifying test code, offering flexibility and scalability in large automation suites.


2) Explain the TestNG lifecycle with annotations and their execution order.

The TestNG lifecycle defines how tests are initialized, executed, and terminated. It is controlled through annotations that provide structure and clarity to the test flow.

Annotation Description Execution Order
@BeforeSuite Runs before all tests in the suite 1
@BeforeTest Executes before <test> tag in XML 2
@BeforeClass Runs before the first method in the current class 3
@BeforeMethod Executes before each test method 4
@Test Contains actual test logic 5
@AfterMethod Runs after each test method 6
@AfterClass Runs after all methods in the class 7
@AfterTest Runs after <test> tag in XML 8
@AfterSuite Executes after all tests in the suite 9

This structured order ensures predictable test setup and teardown, crucial for maintaining test independence.


3) How is TestNG different from JUnit?

While both frameworks are used for unit testing, TestNG provides more robust configuration and parallel execution capabilities.

Feature JUnit TestNG
Parallel Execution Limited support Full support
Annotations Fewer (@Before, @After) Richer (@BeforeSuite, @DataProvider)
Dependency Management Not available Available using dependsOnMethods
Grouping Not supported Supported using groups
Parameterization Through external runners Built-in via XML or @DataProvider

In summary, TestNG is preferred for enterprise-level automation testing and integration with tools like Selenium, whereas JUnit is ideal for simpler unit tests.


4) What are TestNG annotations and how are they useful?

Annotations in TestNG define the structure and behavior of test methods. They eliminate the need for complex XML configuration by providing declarative test control directly in the code.

Commonly used annotations include:

  • @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod
  • @Test
  • @AfterMethod, @AfterClass, @AfterTest, @AfterSuite

Example:

@BeforeMethod
public void setup() {
    System.out.println("Initializing browser...");
}

@Test
public void verifyLogin() {
    System.out.println("Executing login test...");
}

This helps developers organize test execution logically, ensuring that setup, test execution, and teardown occur in a defined order.


5) Explain the concept of grouping in TestNG.

Grouping in TestNG allows logical categorization of tests into smaller, manageable sets such as “Smoke”, “Regression”, or “Sanity”.

Example:

@Test(groups = {"Smoke"})
public void loginTest() { ... }
@Test(groups = {"Regression"})
public void paymentTest() { ... }

You can configure your XML suite to run specific groups:

<groups>
  <run>
    <include name="Smoke"/>
  </run>
</groups>

Benefits:

  • Facilitates selective execution of test cases.
  • Enhances flexibility in CI/CD pipelines.
  • Saves execution time during incremental builds.

6) How can parameterization be achieved in TestNG?

Parameterization enables data-driven testing, allowing tests to run with multiple input datasets. TestNG supports two primary methods:

  1. Using @Parameters annotation with XML:
  2. <parameter name="browser" value="chrome"/>
    @Test
    @Parameters("browser")
    public void launchBrowser(String browser) { ... }
    
  3. Using @DataProvider:
  4. @DataProvider(name="loginData")
    public Object[][] getData() {
      return new Object[][] {{"user1","pass1"}, {"user2","pass2"}};
    }
    
    @Test(dataProvider="loginData")
    public void loginTest(String user, String pass) { ... }
    

This flexibility makes it easier to maintain and execute large test sets across environments or configurations.


7) What are dependencies in TestNG and how are they managed?

Dependencies in TestNG control the order of test execution based on other test results using the dependsOnMethods or dependsOnGroups attributes.

Example:

@Test
public void loginTest() { ... }

@Test(dependsOnMethods = {"loginTest"})
public void verifyDashboard() { ... }

If the dependent method fails, the subsequent test is skipped automatically.

This mechanism prevents invalid test execution and helps maintain logical test integrity. It is especially useful for multi-step functional flows like login โ†’ perform action โ†’ verify result.


8) What are the different ways to execute TestNG tests?

TestNG tests can be executed in several flexible ways depending on the testing setup:

  1. From IDE (Eclipse/IntelliJ): Right-click on the class or XML file โ†’ Run as โ†’ TestNG Test.
  2. From Command Line: java -cp "path\testng.jar;bin" org.testng.TestNG testng.xml
  3. Using Build Tools:
    • Maven: Configure surefire-plugin in pom.xml.
    • Gradle: Use testng dependency and task configuration.
  4. Through CI/CD Pipelines: Integrated with Jenkins or GitHub Actions for automated execution.

This variety ensures compatibility across development, testing, and production environments.


9) What are TestNG listeners and why are they important?

Listeners in TestNG provide hooks to customize test behavior by monitoring test execution events such as start, success, failure, or skip.

Common listeners:

  • ITestListener: Tracks test method-level events.
  • ISuiteListener: Observes suite-level events.
  • IReporter: Generates custom reports.

Example:

public class CustomListener implements ITestListener {
  public void onTestFailure(ITestResult result) {
    System.out.println("Test Failed: " + result.getName());
  }
}

Listeners are often used for taking screenshots on failure, generating custom logs, or integrating with reporting tools like Allure or ExtentReports.


10) What are the advantages and disadvantages of using TestNG?

Aspect Advantages Disadvantages
Flexibility Supports grouping, dependency, and parallel execution Complex XML setup for large suites
Reporting Provides detailed HTML and XML reports Limited customization without listeners
Integration Works seamlessly with Selenium and CI/CD tools Slightly higher learning curve
Parameterization Built-in support for data-driven testing Requires maintenance for large datasets

Overall, TestNG is a robust and flexible framework suitable for modern automation testing environments despite its minor configuration overhead.


11) How can you prioritize test cases in TestNG?

TestNG provides the priority attribute in the @Test annotation to define the order in which test methods should execute. Tests with lower priority values run first.

Example:

@Test(priority = 1)
public void loginTest() { ... }

@Test(priority = 2)
public void dashboardTest() { ... }

If no priority is specified, the default value is 0, and methods execute alphabetically.

Best Practice: Use priority values sparingly. Overusing them can make the test order rigid. For complex flows, dependency management (dependsOnMethods) is more maintainable than strict prioritization.


12) Explain the concept and use of parallel execution in TestNG.

Parallel execution in TestNG allows multiple tests, classes, or methods to run simultaneously, significantly reducing overall execution time.

You can enable this feature in the testng.xml file:

<suite name="ParallelSuite" parallel="tests" thread-count="3">
  <test name="Test1">...</test>
  <test name="Test2">...</test>
</suite>

Parallel modes supported:

  • tests
  • classes
  • methods
  • instances

Advantages:

  • Faster feedback cycle.
  • Efficient utilization of multi-core processors.
  • Scalability for large automation suites.

However, ensure thread safety when using shared resources like WebDriver or database connections.


13) What are data providers in TestNG? How do they differ from parameters?

@DataProvider enables data-driven testing by supplying test methods with multiple sets of data.

Example:

@DataProvider(name="credentials")
public Object[][] data() {
    return new Object[][] {{"user1", "pass1"}, {"user2", "pass2"}};
}

@Test(dataProvider="credentials")
public void login(String username, String password) { ... }

Difference between @Parameters and @DataProvider:

Feature @Parameters @DataProvider
Data Source XML file Java method
Data Type Single data set Multiple data sets
Flexibility Less High
Use Case Environment variables Repeated data-driven tests

Hence, @DataProvider is preferred when executing a single test with multiple datasets, such as verifying login with multiple credentials.


14) How can you disable or skip a test in TestNG?

You can disable a test in TestNG using the enabled attribute or by programmatically skipping it.

1. Using enabled = false:

@Test(enabled = false)
public void skipTest() {
    System.out.println("This test will not run.");
}

2. Skipping during runtime using SkipException:

@Test
public void conditionalSkip() {
    throw new SkipException("Skipping this test due to condition.");
}

Disabling is useful for temporarily deactivating unstable or incomplete tests without deleting them. Skipping is valuable for runtime conditions, like skipping tests for unsupported browsers.


15) What is the role of testng.xml file and what are its major components?

The testng.xml file is the configuration backbone of TestNG. It defines test suites, test groups, parameters, and parallel execution setup.

Structure Example:

<suite name="AutomationSuite">
  <parameter name="browser" value="chrome"/>
  <test name="RegressionTests">
    <classes>
      <class name="com.test.LoginTest"/>
      <class name="com.test.PaymentTest"/>
    </classes>
  </test>
</suite>

Major Components:

  • <suite> โ€“ Defines the entire suite.
  • <test> โ€“ Represents a test block.
  • <classes> โ€“ Lists test classes.
  • <methods> โ€“ Filters specific test methods.
  • <parameter> โ€“ Provides global or test-level parameters.

The XML file provides centralized control over execution without changing the code.


16) How can you generate reports in TestNG?

TestNG automatically generates two types of reports:

  1. HTML Report (test-output/index.html) โ€“ Summarizes passed, failed, and skipped tests.
  2. XML Report โ€“ Used for integration with CI/CD tools.

For advanced reporting, TestNG integrates with:

  • ExtentReports โ€“ Offers graphical dashboards and detailed logs.
  • Allure Reports โ€“ Provides visual analytics with test steps, screenshots, and logs.

Example Integration:

ExtentReports extent = new ExtentReports();
ExtentTest test = extent.createTest("Login Test");
test.pass("Test Passed Successfully");
extent.flush();

These reports are essential for tracking trends and identifying weak areas in test coverage.


17) What are factories in TestNG, and how do they work?

Factories in TestNG are used to create dynamic instances of test classes. They allow parameterized instantiation of classes before running tests.

Example:

public class FactoryExample {
  private String browser;

  public FactoryExample(String browser) {
    this.browser = browser;
  }

  @Factory
  public static Object[] factoryMethod() {
    return new Object[] { new FactoryExample("Chrome"), new FactoryExample("Firefox") };
  }

  @Test
  public void testBrowser() {
    System.out.println("Running test on: " + browser);
  }
}

Advantages:

  • Enables parameterized object creation.
  • Ideal for cross-browser testing and multi-environment execution.
    Factories complement DataProviders when you need different object configurations rather than just method-level data variation.

18) How can you use assertions in TestNG?

Assertions are used to validate expected versus actual results within test methods.

Types of Assertions:

  1. Hard Assertions (Assert class):
    Stops test execution immediately upon failure.
  2. Assert.assertEquals(actual, expected);
    Assert.assertTrue(condition);
    
  3. Soft Assertions (SoftAssert class):
    Continues execution even after failure, reporting all issues at the end.
  4. SoftAssert soft = new SoftAssert();
        soft.assertEquals(actual, expected);
        soft.assertAll();
    
  5. When to Use:
    • Use hard assertions for critical validation like login success.
    • Use soft assertions for multiple verifications within a single test method.

19) Explain the difference between @BeforeMethod and @BeforeClass in TestNG.

Aspect @BeforeMethod @BeforeClass
Execution Runs before each test method Runs once before any method in the class
Scope Per test method Per test class
Common Use Initializing browser before every test Loading configuration or browser setup once

Example:

@BeforeClass
public void setupClass() {
    System.out.println("Executed once per class");
}

@BeforeMethod
public void setupMethod() {
    System.out.println("Executed before each method");
}

Use @BeforeMethod when each test needs a clean environment, and @BeforeClass for heavy initialization tasks that can be reused.


20) How does TestNG support dependency injection and what are its use cases?

TestNG supports dependency injection through built-in injection of context and configuration objects such as ITestContext, XmlTest, or Method.

Example:

@Test
public void testContextExample(ITestContext context) {
    System.out.println("Suite Name: " + context.getSuite().getName());
}

Use Cases:

  • Fetching test parameters dynamically.
  • Accessing configuration information like suite names or parallel execution settings.
  • Enhancing test flexibility without hardcoding dependencies.

Dependency injection allows developers to write modular, context-aware tests that adapt dynamically to environment changes.


21) What is the difference between @Factory and @DataProvider in TestNG?

Both @Factory and @DataProvider help with parameterization, but they operate at different levels in the test architecture.

Feature @Factory @DataProvider
Scope Class level Method level
Purpose Creates multiple instances of a class with different data Supplies data to a single test method
Execution Executes the entire class for each instance Executes one method multiple times
Ideal Use Case Cross-browser or environment testing Data-driven functional testing

Example:

  • Factory: Runs the whole class per browser type.
  • DataProvider: Runs one test method with multiple data sets.

Use @Factory when object instantiation itself varies, and @DataProvider for functional input variation within the same object instance.


22) How can you retry failed test cases automatically in TestNG?

TestNG provides a mechanism to rerun failed test cases using the IRetryAnalyzer interface.

Example Implementation:

public class RetryAnalyzer implements IRetryAnalyzer {
  int count = 0;
  int maxTry = 2;

  public boolean retry(ITestResult result) {
    if (count < maxTry) {
      count++;
      return true;
    }
    return false;
  }
}

Usage:

@Test(retryAnalyzer = RetryAnalyzer.class)
public void testLogin() {
   Assert.fail("Intentional Failure");
}

Benefits:

  • Reduces flakiness in CI pipelines.
  • Handles transient network or environment issues.

Best Practice: Combine retry logic with proper logging and screenshots for debugging intermittent failures.


23) What is the use of ITestContext in TestNG?

ITestContext provides contextual information about the test run, including suite name, test name, output directory, and parameters.

Example:

@Test
public void contextExample(ITestContext context) {
    System.out.println("Suite: " + context.getSuite().getName());
}

Key Methods:

  • getSuite() โ€“ Retrieves suite-level info.
  • getName() โ€“ Returns the test name.
  • setAttribute() / getAttribute() โ€“ Share data between tests.

It enables data sharing across test methods or classes and facilitates dynamic reporting and logging.


24) How can you create dependency between test groups in TestNG?

You can define inter-group dependencies using the dependsOnGroups attribute in the @Test annotation.

Example:

@Test(groups = "Login")
public void login() { ... }

@Test(dependsOnGroups = "Login")
public void verifyProfile() { ... }

This ensures that the verifyProfile group runs only if all tests in the Login group pass successfully.

It is particularly useful in integration testing, where modules depend on the successful execution of others (e.g., login โ†’ profile โ†’ logout flow).


25) How can you ignore certain test methods in a TestNG XML file?

You can explicitly exclude methods within a class in the XML suite file using <exclude> tags.

Example:

<class name="com.test.LoginTests">
  <methods>
    <exclude name="verifyLogout"/>
  </methods>
</class>

This allows testers to disable specific methods temporarily without modifying the Java source code โ€” useful in large suites where dynamic inclusion or exclusion is needed based on release cycles or sprint priorities.


26) How can TestNG be integrated with Selenium WebDriver?

TestNG and Selenium form a powerful combination for UI automation.

A typical integration setup involves organizing tests using annotations, managing setup/teardown, and running tests via XML or CI tools.

Example:

@BeforeMethod
public void setup() {
    driver = new ChromeDriver();
}

@Test
public void verifyTitle() {
    driver.get("https://example.com");
    Assert.assertEquals(driver.getTitle(), "Example Domain");
}

@AfterMethod
public void teardown() {
    driver.quit();
}

Integration Benefits:

  • Enables parallel browser testing.
  • Simplifies test grouping and reporting.
  • Works seamlessly with CI/CD pipelines like Jenkins or GitHub Actions.

27) What are some best practices when using TestNG in large automation frameworks?

Best Practices:

  1. Use Descriptive Naming: Name tests based on behavior, not implementation.
  2. Leverage Grouping: Create logical test groups (Smoke, Regression).
  3. Avoid Hardcoding: Use parameters or property files for test data.
  4. Minimize Dependencies: Keep test cases independent wherever possible.
  5. Centralize Configuration: Use testng.xml for suite setup.
  6. Integrate Reporting: Use listeners or third-party tools like ExtentReports.
  7. Use Retry Logic Cautiously: Avoid masking genuine defects.

Following these ensures scalability, maintainability, and readability in enterprise-level automation.


28) What is the difference between @BeforeTest and @BeforeSuite in TestNG?

Feature @BeforeTest @BeforeSuite
Scope Runs before each <test> tag in XML Runs once before the entire suite
Frequency Multiple times (if multiple <test> blocks) Only once per suite
Common Use Initialize test-level configuration Set up global resources

Example:

@BeforeSuite
public void setupSuite() {
    System.out.println("Global setup for suite.");
}

@BeforeTest
public void setupTest() {
    System.out.println("Setup for each <test> tag.");
}

Use @BeforeSuite for global configurations (e.g., database connection) and @BeforeTest for test-specific initializations.


29) Can TestNG be used for API testing? How?

Yes. TestNG can be effectively used for API testing by integrating with HTTP client libraries like RestAssured or HttpClient.

Example:

@Test
public void verifyApiResponse() {
    Response response = RestAssured.get("https://api.example.com/users");
    Assert.assertEquals(response.getStatusCode(), 200);
}

Advantages:

  • Enables assertion-based validation of responses.
  • Supports parameterization and data-driven testing for multiple endpoints.
  • Generates structured reports for REST API validations.

By combining TestNG and RestAssured, testers can maintain a unified automation framework for both UI and API testing.


30) How do you pass parameters from the command line in TestNG?

You can override XML parameters at runtime by passing system properties using the -D flag.

Command Example:

mvn test -Dbrowser=chrome -Denv=staging

Code Example:

@Parameters("browser")
@Test
public void launch(@Optional("firefox") String browser) {
    System.out.println("Running on: " + browser);
}

This enables dynamic environment selection in CI/CD pipelines without changing configuration files, enhancing test flexibility.


31) How can you control test execution order in TestNG without using priorities?

Instead of using priority, TestNG allows control through dependencies and XML method ordering.

Methods:

  1. Using dependsOnMethods:
  2. @Test
    public void login() { ... }
    
    @Test(dependsOnMethods = "login")
    public void verifyDashboard() { ... }
    
  3. Using XML Method Sequence:
  4. <classes>
      <class name="com.test.LoginTests">
        <methods>
          <include name="login"/>
          <include name="verifyDashboard"/>
        </methods>
      </class>
    </classes>
    

Best Practice: Prefer logical dependencies for complex flows instead of static priorities, ensuring robust, maintainable test suites.


32) How can you execute specific test methods from the command line in TestNG?

TestNG allows method-level test execution directly from the command line using XML or Maven Surefire configurations.

Option 1: Using XML File

<class name="com.test.LoginTests">
  <methods>
    <include name="verifyLogin"/>
  </methods>
</class>

Option 2: Maven Command

mvn test -Dtest=com.test.LoginTests#verifyLogin

This approach allows selective execution, useful for debugging individual methods or validating critical functionalities during quick builds.


33) How do you parameterize tests using an external Excel file in TestNG?

Excel-driven parameterization is common in data-driven frameworks where test data changes frequently.

Implementation Steps:

  1. Use Apache POI or JExcel to read Excel data.
  2. Feed it into a @DataProvider method.

Example:

@DataProvider(name = "excelData")
public Object[][] readExcel() throws Exception {
    FileInputStream fis = new FileInputStream("data.xlsx");
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    XSSFSheet sheet = wb.getSheetAt(0);
    Object[][] data = new Object[sheet.getLastRowNum()][2];
    for (int i = 0; i < sheet.getLastRowNum(); i++) {
        data[i][0] = sheet.getRow(i + 1).getCell(0).getStringCellValue();
        data[i][1] = sheet.getRow(i + 1).getCell(1).getStringCellValue();
    }
    return data;
}

This allows running the same test method with multiple real-world data sets from Excel, increasing flexibility and coverage.


34) How can you run TestNG tests in Jenkins or CI/CD pipelines?

TestNG integrates seamlessly with Jenkins, GitLab CI, or GitHub Actions through Maven or Gradle builds.

Steps in Jenkins:

  1. Install Maven Integration Plugin.
  2. Create a Freestyle or Pipeline Job.
  3. Add mvn clean test as a build step.
  4. Post-build, configure HTML reports:
    • Report directory: test-output
    • Index file: index.html

Benefits:

  • Enables automated regression testing.
  • Provides scheduled test runs and trend tracking.
  • Ensures consistent test execution across environments.

35) What is the purpose of @Parameters and how is it different from @Optional?

Both annotations deal with parameterization but serve distinct purposes.

Feature @Parameters @Optional
Purpose Passes parameters from XML file Provides default value if parameter is missing
Declaration Used with XML <parameter> Used inside test method
Behavior Throws error if value missing Uses fallback value

Example:

@Test
@Parameters("browser")
public void runTest(@Optional("chrome") String browser) {
    System.out.println("Running on: " + browser);
}

Using @Optional ensures test stability when XML configurations are incomplete.


36) How do you handle test dependencies across different classes in TestNG?

To create inter-class dependencies, TestNG allows using the dependsOnGroups attribute.

Example:

@Test(groups = "Login")
public void loginTest() { ... }

@Test(groups = "Dashboard", dependsOnGroups = "Login")
public void dashboardTest() { ... }

This approach helps manage multi-module dependencies where each class represents a module (Login, Dashboard, Payment, etc.).

It ensures that dependent modules execute only if prerequisite tests succeed, maintaining test integrity.


37) What are configuration failures in TestNG, and how can they be handled?

Configuration failures occur when setup or teardown methods annotated with @Before* or @After* fail.

They can cause dependent tests to skip, even if those tests are correct.

Common Causes:

  • Incorrect WebDriver initialization.
  • Database or environment setup issues.
  • Parameter misconfiguration.

Solutions:

  • Use try-catch blocks in setup methods.
  • Apply alwaysRun = true to ensure cleanup runs despite failures.

Example:

@BeforeMethod(alwaysRun = true)
public void setup() {
    // Setup logic
}

This ensures your teardown methods still execute, maintaining test environment stability.


38) What is the use of invocationCount and threadPoolSize attributes in TestNG?

These attributes allow repeated and parallel test execution of the same method.

Example:

@Test(invocationCount = 5, threadPoolSize = 2)
public void loadTest() {
    System.out.println("Running load test...");
}
Attribute Description
invocationCount Number of times a method runs
threadPoolSize Number of concurrent threads

Use Case: Performance testing, stability verification, or reproducing flaky behavior under multiple runs.


39) How do you run only failed test cases in TestNG?

After a suite run, TestNG generates a file named testng-failed.xml in the test-output directory.

You can rerun only failed tests by executing:

java -cp testng.jar org.testng.TestNG test-output/testng-failed.xml

Advantages:

  • Saves time by skipping successful tests.
  • Facilitates debugging in large suites.
  • Commonly used in CI pipelines for quick retests.

You can also integrate this with Jenkins using a post-build script for reruns.


40) What are some limitations of TestNG and how can they be mitigated?

Despite its robustness, TestNG has a few limitations.

Limitation Mitigation Strategy
XML configuration complexity Use annotation-based configuration and builders
Limited native reporting Integrate ExtentReports or Allure
No built-in retry control Implement IRetryAnalyzer
Thread-safety concerns in parallel runs Use thread-local WebDriver instances
Learning curve for beginners Maintain template-based project structures

With proper framework design and best practices, these limitations can be minimized, ensuring stable and maintainable automation solutions.


41) How do you use listeners for logging and capturing screenshots in Selenium-TestNG?

Listeners in TestNG help monitor test execution and perform actions such as logging, taking screenshots, or reporting results dynamically.

Example Implementation:

public class ScreenshotListener implements ITestListener {
  @Override
  public void onTestFailure(ITestResult result) {
      WebDriver driver = ((BaseTest) result.getInstance()).getDriver();
      File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(src, new File("screenshots/" + result.getName() + ".png"));
  }
}

Usage:

@Listeners(ScreenshotListener.class)
public class LoginTests extends BaseTest { ... }

Benefits:

  • Captures failures automatically.
  • Improves debugging through visual evidence.
  • Reduces manual effort in maintaining logs.

This technique is crucial in CI/CD automation pipelines, especially when diagnosing failed builds remotely.


42) What is the difference between IReporter and ITestListener in TestNG?

Feature IReporter ITestListener
Purpose Generates custom reports post-test execution Tracks and reacts to runtime test events
Invocation After all tests complete During test lifecycle (start, success, failure)
Output HTML/XML/JSON reports Log files, screenshots, live dashboards
Common Use ExtentReports, Allure integration Logging, failure handling, retry mechanisms

Example:

  • Use IReporter for building comprehensive reports after test completion.
  • Use ITestListener for real-time logging or screenshots.

They can also be combined to build end-to-end automation analytics systems.


43) How do you perform cross-browser testing using TestNG XML configuration?

Cross-browser testing ensures that the same functionality works across different browsers.

Example Configuration:

<suite name="CrossBrowserSuite" parallel="tests">
  <test name="ChromeTest">
    <parameter name="browser" value="chrome"/>
    <classes><class name="com.test.LoginTest"/></classes>
  </test>
  <test name="FirefoxTest">
    <parameter name="browser" value="firefox"/>
    <classes><class name="com.test.LoginTest"/></classes>
  </test>
</suite>

Java Code:

@Parameters("browser")
@BeforeClass
public void setup(String browser) {
    if(browser.equalsIgnoreCase("chrome"))
        driver = new ChromeDriver();
    else if(browser.equalsIgnoreCase("firefox"))
        driver = new FirefoxDriver();
}

This approach enables parallel, multi-browser execution, accelerating test coverage across platforms.


44) How do you integrate TestNG with Docker or Selenium Grid?

TestNG integrates seamlessly with Dockerized Selenium Grid to enable distributed parallel testing.

Steps:

  1. Set up Selenium Grid in Docker using the official Selenium image:
    docker run -d -p 4444:4444 --name selenium-grid selenium/standalone-chrome
  2. Update TestNG setup:
  3. DesiredCapabilities caps = new DesiredCapabilities();
    caps.setBrowserName("chrome");
    driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), caps);
    
  4. Execute your suite via Jenkins or CI pipeline.

Benefits:

  • Enables scalable parallel testing.
  • Reduces environment setup overhead.
  • Provides consistent test execution across distributed containers.

45) What is the difference between parallel execution at suite, test, and method levels in TestNG?

Level Parallel Attribute Execution Behavior
Suite parallel="suites" Executes multiple suites concurrently
Test parallel="tests" Runs <test> blocks simultaneously
Class parallel="classes" Runs test classes in parallel
Method parallel="methods" Executes individual test methods in parallel

Example:

<suite name="ParallelTests" parallel="methods" thread-count="3">
  <test name="SampleTest">
    <classes><class name="com.test.ParallelExample"/></classes>
  </test>
</suite>

Best Practice:Use parallel="classes" for stability in Selenium tests to avoid shared driver conflicts.


46) How can you share data between tests without using global variables in TestNG?

TestNG provides ITestContext and dependency injection to share data dynamically.

Example:

@Test
public void storeData(ITestContext context) {
    context.setAttribute("token", "abc123");
}

@Test(dependsOnMethods = "storeData")
public void useData(ITestContext context) {
    String token = (String) context.getAttribute("token");
    System.out.println("Using token: " + token);
}

This avoids static variables, maintains thread safety, and ensures data isolation across tests.


47) How do you capture and log skipped tests in TestNG?

You can capture skipped tests using onTestSkipped() in the ITestListener interface.

Example:

@Override
public void onTestSkipped(ITestResult result) {
    System.out.println("Skipped Test: " + result.getName());
}

Reasons for Skipping:

  • Dependent test failure.
  • Conditional skipping via SkipException.
  • Environment unavailability.

Best Practice:
Log skip reasons and stack traces for traceability in CI reports or dashboards.


48) Explain how to parameterize REST API tests using TestNG and RestAssured.

TestNG’s @DataProvider integrates elegantly with RestAssured for API parameterization.

Example:

@DataProvider(name = "apiData")
public Object[][] apiData() {
  return new Object[][] {
    {"https://api.example.com/users/1"},
    {"https://api.example.com/users/2"}
  };
}

@Test(dataProvider = "apiData")
public void testApi(String url) {
  Response response = RestAssured.get(url);
  Assert.assertEquals(response.getStatusCode(), 200);
}

Advantages:

  • Executes the same API call for multiple endpoints or payloads.
  • Simplifies regression testing for APIs with varying input sets.
  • Integrates seamlessly with CI tools and reports.

49) How do you create custom annotations in TestNG for reusable testing patterns?

Custom annotations can standardize repetitive test configurations or validations.

Example:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SmokeTest {
  String description() default "Smoke Test";
}

Usage:

@SmokeTest(description="Validating Login Functionality")
@Test
public void loginTest() { ... }

Combined with reflection, you can dynamically read these annotations to group tests or drive conditional execution.

This technique is widely used in framework meta-programming to build self-documenting tests.


50) How can you combine Cucumber and TestNG for hybrid testing frameworks?

TestNG can act as the test runner for Cucumber BDD scenarios, offering powerful reporting and parallelization.

Example Runner:

@CucumberOptions(
  features = "src/test/resources/features",
  glue = "stepDefinitions",
  plugin = {"pretty", "html:target/cucumber-report.html"}
)
public class RunCucumberTest extends AbstractTestNGCucumberTests { }

Advantages:

  • Leverages TestNG’s annotations, listeners, and reporting.
  • Supports parallel feature execution.
  • Integrates with Allure and ExtentReports easily.

This hybrid approach merges BDD readability with TestNG flexibility, ideal for enterprise-grade frameworks.


๐Ÿ” Top TestNG Interview Questions with Real-World Scenarios & Strategic Responses

Below are 10 realistic, domain-relevant TestNG interview questions along with clear expectations and strong example answers.

1) Can you explain the key advantages of using TestNG compared to JUnit?

Expected from candidate: Demonstrate understanding of TestNG’s enhanced features and why it is often preferred for enterprise automation.

Example answer: “TestNG provides several advantages such as flexible test configuration, support for parallel execution, dependent test methods, data-driven testing with DataProviders, and built-in reporting. These capabilities make TestNG more powerful for complex automation frameworks that require scalability.”


2) How do you use TestNG annotations to control test execution flow?

Expected from candidate: Knowledge of annotation purpose and order.

Example answer: “TestNG offers annotations such as @BeforeSuite, @BeforeClass, @BeforeMethod, @Test, and their corresponding teardown annotations. These allow structured organization of test setup and cleanup. For example, @BeforeMethod executes before each test method, which is useful for initializing browser state.”


3) Describe a challenging automation project where TestNG played a key role.

Expected from candidate: Real project experience and ability to articulate problem-solving.

Example answer: “In my previous role, I worked on a project that required extensive regression testing across multiple environments. TestNG’s parallel execution and grouping features allowed the team to run critical suites simultaneously, reducing execution time significantly while maintaining reliability.”


4) How do TestNG groups help in organizing and executing tests efficiently?

Expected from candidate: Understanding of grouping, including include/exclude mechanisms.

Example answer: “Groups in TestNG allow categorization of test cases such as smoke, regression, and integration. By using testng.xml, I can selectively run groups, exclude unstable tests, and manage different test suites without modifying the code itself.”


5) Describe a situation where you had to debug failing TestNG tests. What was your approach?

Expected from candidate: Critical thinking and troubleshooting skills.

Example answer: “At a previous position, I encountered a set of failing TestNG tests that appeared to pass locally but failed in CI. I enabled detailed logging, reviewed execution order, and discovered that a shared resource was not being reset between tests. I then implemented proper teardown steps using @AfterMethod to ensure test isolation.”


6) How do you implement data-driven testing using TestNG?

Expected from candidate: Understanding of DataProviders and use cases.

Example answer: “I create a @DataProvider method that returns data in Object arrays and then bind it to a @Test method using the dataProvider attribute. This allows multiple iterations of the same test with different input sets, which is useful for validating form submissions or API payload variations.”


7) How do you manage test dependencies in TestNG?

Expected from candidate: Proper use of dependsOnMethods or dependsOnGroups.

Example answer: “TestNG allows test dependencies through the dependsOnMethods and dependsOnGroups attributes. I use dependencies when a test must execute only after another completes successfully, such as verifying an order only after creating it.”


8) Describe how you have used TestNG with continuous integration tools.

Expected from candidate: Real-world automation pipeline experience.

Example answer: “At my previous job, I integrated TestNG with Jenkins by configuring the Maven build to generate TestNG HTML and XML reports. Jenkins then archived the reports and displayed results after each build cycle. This integration helped the team track failures quickly and maintain release stability.”


9) Tell me about a time when you had to work under tight deadlines while managing multiple automation tasks.

Expected from candidate: Time management and ability to prioritize.

Example answer: “In my last role, I needed to update existing TestNG test suites while also creating new ones for an upcoming release. I prioritized tasks based on business impact, automated the highest-risk areas first, and used TestNG grouping to isolate completed sections for early review. This ensured timely delivery without compromising quality.”


10) How would you design a scalable TestNG framework for a large application?

Expected from candidate: Architecture understanding, patterns, and best practices.

Example answer: “I would design a modular framework using the Page Object Model, integrate TestNG for execution management, and use DataProviders for data-driven scenarios. I would also configure parallel execution, centralize utilities, and externalize configuration settings so the framework remains scalable and maintainable as the application grows.”

Summarize this post with: