25 TestNG Interview Questions and Answers
Twenty-five TestNG questions from basic to tricky, with crisp answers and working Java snippets for listeners, retries, data providers and parallel runs.
TestNG questions are rarely the hardest part of a Selenium interview, but they are where small gaps show. A candidate who says @BeforeTest runs before every test method, or who has never wondered why their soft assertions never fail, signals that they have used a framework someone else built. The good news is that the set of TestNG interview questions is fairly predictable, and each one has a clear, correct answer.
Below are 25 questions grouped into basics, test control, data and parameters, parallel execution, and listeners and reporting. Answers are short enough to speak in an interview, and code samples work with TestNG 7 and Java 17. If you want to learn the framework step by step first, start with our TestNG tutorial.
Key takeaways
- Annotation execution order and
@BeforeTestvs@BeforeMethodare asked in almost every round. - Know how to control tests: priority, groups, dependencies, skipping, timeouts and expected exceptions.
- Be able to write a
@DataProviderand explain how it differs from@Parameters. - Parallel runs need thread-safe drivers; mention
ThreadLocalwithout being asked. - Listeners and retry analysers show framework depth; prepare one real example of each.
Basic TestNG interview questions (1-5)
1. What is TestNG and why do testers use it?
TestNG is a Java testing framework that provides annotations, assertions, grouping, data-driven testing, parallel execution, listeners and reports. Selenium handles the browser; TestNG organises and runs the tests and reports results.
2. What is the execution order of TestNG annotations?
@BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, @AfterMethod, @AfterClass, @AfterTest, @AfterSuite. @BeforeGroups and @AfterGroups run around the first and last test of a group.
3. What is the difference between @BeforeTest and @BeforeMethod?
@BeforeTest runs once before each <test> tag in testng.xml, which may include many classes. @BeforeMethod runs before every single @Test method. Browser launch for independent tests belongs in @BeforeMethod.
4. How is TestNG different from JUnit 5?
Both are mature. TestNG has built-in XML suites, groups, data providers, dependencies and parallel configuration. JUnit 5 offers similar features through tags, parameterised tests and extensions, and is the default in many developer teams. In Selenium projects in India, TestNG remains very common.
5. Which assertion order does TestNG use?
Assert.assertEquals(actual, expected, message). JUnit uses expected first. Swapping them produces misleading failure messages, which interviewers sometimes check.
Controlling test execution (6-12)
6. How do you set the order of tests?
Use priority. Lower values run first, and the default is 0. Methods without a priority, or with equal priority, run in an order TestNG determines, commonly alphabetical by method name. Relying heavily on order is a design smell; tests should be independent.
7. How do you skip or disable a test?
Set enabled = false on @Test to disable it. To skip at runtime based on a condition, throw SkipException:
import org.testng.SkipException;
import org.testng.annotations.Test;
public class FeatureTests {
@Test
public void upiPaymentFlow() {
boolean upiEnabled = Boolean.parseBoolean(System.getProperty("upi.enabled", "false"));
if (!upiEnabled) {
throw new SkipException("UPI is disabled in this environment");
}
// test steps
}
}8. How do test dependencies work?
dependsOnMethods or dependsOnGroups makes a test run only after the named methods or groups pass. If they fail, the dependent test is skipped, not failed. alwaysRun = true makes it run regardless. Use dependencies sparingly because they block parallel runs and make failures cascade.
9. How do you use groups?
Add groups = {"smoke", "checkout"} to @Test, then include or exclude groups in testng.xml under <groups><run>. Groups let one codebase serve smoke, sanity and regression runs. For the difference between those suites, see our guide on smoke vs sanity testing.
10. How do you test that an exception is thrown?
@Test(expectedExceptions = IllegalArgumentException.class)
public void negativeAmountIsRejected() {
new Wallet().debit(-100);
}The test passes only if that exception (or a subclass) is thrown. expectedExceptionsMessageRegExp can also check the message.
11. What does timeOut do?
@Test(timeOut = 5000) fails the test if it runs longer than 5,000 milliseconds. It is useful for catching hangs, but explicit waits remain the right tool for UI timing.
12. What are invocationCount and threadPoolSize?
invocationCount = 5 runs the same test five times. With threadPoolSize = 3, those invocations run on up to three threads. Teams use this to reproduce flaky behaviour or for simple concurrency checks.
Data and parameters (13-16)
13. How do you write a DataProvider?
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"valid@test.com", "Correct@123", true},
{"valid@test.com", "wrong", false},
{"", "Correct@123", false}
};
}
@Test(dataProvider = "loginData")
public void login(String email, String password, boolean shouldPass) {
// perform login and assert based on shouldPass
}To keep data providers in a separate class, make the method static and use dataProviderClass = LoginData.class on the test.
14. What is the difference between @Parameters and @DataProvider?
@Parameters reads single values from testng.xml, such as the browser or environment, and runs the method once. @DataProvider supplies many rows from code or files and runs the test once per row. Use parameters for configuration and data providers for test data.
15. How do you give a parameter a default value?
Use @Optional:
@Parameters("browser")
@BeforeMethod
public void setUp(@Optional("chrome") String browser) {
System.out.println("Browser: " + browser);
}Without @Optional, a missing parameter causes a configuration failure.
16. Can a DataProvider run in parallel?
Yes. Set @DataProvider(parallel = true). The thread count comes from the data-provider-thread-count attribute in the suite file, which defaults to 10.
Parallel execution (17-19)
17. Which parallel modes does TestNG support?
In testng.xml, parallel can be methods, classes, tests or instances, with thread-count setting the number of threads. Choose classes if tests within a class share state; methods gives more parallelism but demands complete independence.
18. How do you make WebDriver thread-safe?
Store the driver in a ThreadLocal:
public class DriverManager {
private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();
public static WebDriver get() {
return DRIVER.get();
}
public static void set(WebDriver driver) {
DRIVER.set(driver);
}
public static void quit() {
if (DRIVER.get() != null) {
DRIVER.get().quit();
DRIVER.remove();
}
}
}Calling remove() prevents leaks when threads are reused. This topic also comes up in Java interview questions for testers.
19. What problems appear when running in parallel?
Shared static state, tests that depend on each other, shared test accounts and data collisions. Fixes include per-thread drivers, unique test data per test and avoiding dependsOnMethods across parallel tests.
Listeners, retries and reporting (20-25)
20. What listeners have you used?
ITestListener for test events (start, success, failure, skip), ISuiteListener for suite start and finish, IInvokedMethodListener around every method, and IAnnotationTransformer to change annotations at runtime. Register them with @Listeners or in testng.xml.
21. How do you capture a screenshot on failure?
Implement ITestListener.onTestFailure, get the driver for the current thread, and save a screenshot.
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
WebDriver driver = DriverManager.get();
if (driver == null) {
return;
}
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Path target = Path.of("screenshots", result.getName() + ".png");
try {
Files.createDirectories(target.getParent());
Files.copy(src.toPath(), target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println("Could not save screenshot: " + e.getMessage());
}
}
}22. How do you retry failed tests?
Implement IRetryAnalyzer and attach it with @Test(retryAnalyzer = RetryAnalyzer.class):
public class RetryAnalyzer implements IRetryAnalyzer {
private static final int MAX_RETRIES = 1;
private int attempts = 0;
@Override
public boolean retry(ITestResult result) {
if (attempts < MAX_RETRIES) {
attempts++;
return true;
}
return false;
}
}To apply it to every test, use an IAnnotationTransformer registered in testng.xml. Say clearly in the interview that retries are a safety net for infrastructure flakiness, not a fix for unstable tests.
23. How do you rerun only failed tests?
After a run, TestNG writes testng-failed.xml in the output folder. Running that file executes only the failed tests and their required configuration methods.
24. Which reports does TestNG generate?
By default, an HTML report (index.html) and emailable-report.html in test-output, plus JUnit-style XML that CI tools can read. When run through Maven, results appear under target/surefire-reports. Reporter.log() adds messages to the report. Many teams add Allure or Extent Reports for richer output.
25. How do you run TestNG tests from CI?
Configure the Maven Surefire plugin with the suite file and run mvn test from Jenkins, GitHub Actions or any CI tool. Pass environment values with -D system properties, and publish the XML results so the CI server shows pass and fail counts.
Quick revision table
| Question | Short answer |
|---|---|
| BeforeTest vs BeforeMethod | Per test tag vs per test method |
| Default priority | 0 |
| Skip at runtime | throw SkipException |
| Parameters vs DataProvider | Config values vs rows of data |
| Parallel safety | ThreadLocal driver plus unique data |
| Rerun failures | testng-failed.xml |
| Global retry | IRetryAnalyzer via IAnnotationTransformer |
How to prepare
Build a small project where you can demonstrate every answer: groups for smoke and regression, one data provider reading a CSV, parallel classes with a ThreadLocal driver, a screenshot listener and a retry analyser. Organise it with page objects as shown in our Page Object Model guide. When an interviewer asks a follow-up, you can describe what you actually saw happen. The official TestNG documentation is the best place to confirm attribute names.
🚀 Applying for Selenium with Java roles?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →FAQs
Is TestNG still used in 2026?
Yes. TestNG remains widely used in Selenium with Java frameworks, especially in service companies and enterprise projects. JUnit 5 is also common, so knowing both at some level is useful.
What is testng.xml used for?
It defines suites, tests, classes, groups, parameters, listeners and parallel settings. It lets you run different combinations of tests without changing code.
Can we run TestNG without testng.xml?
Yes. You can run test classes directly from an IDE or with Maven Surefire using includes. The XML file becomes important when you need groups, parameters or parallel configuration.
What happens if a dependent test fails in TestNG?
Tests that depend on it are marked as skipped rather than failed, unless they set alwaysRun = true. Reports show the skip so you can trace the original failure.
How many TestNG interview questions are asked in a Selenium interview?
Usually a handful, often five to ten, mixed with Selenium and Java questions. The ones on annotations, groups, data providers, parallel runs and listeners come up most.
Conclusion
Open your current framework and find where each of these 25 answers lives in your code. Any question you cannot point to in a file is the one to implement this week. Then revise the rest of the stack with our Selenium interview questions.
- 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
- Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
- Certified QA coursesUp to 3 courses included · all 17 for ₹500
- AI ATS Resume BuilderFree resume points included
- Full LinkedQA feedEvery post, fully unblurred
- Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps
Instant activation right after payment · One login for jobs, courses, resume & LinkedQA
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.