TestNG — 30 Interview Questions (Answers & Examples)¶
Testing framework for Java that adds annotations, grouping, parameterization, parallel runs, and rich reporting on top of Selenium.
Q1. What is TestNG and why is it used in Selenium automation?¶
TestNG is a Java testing framework (Next Generation) that provides annotations, assertions, grouping, parameterization, parallel execution, and HTML reports to structure and run Selenium tests.
In plain words: Selenium only drives the browser; TestNG is the harness around it that decides which tests run, in what order, with what data, and produces a pass/fail report.
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class LoginTest {
@Test
public void validLogin() {
// driver.get(...); driver.findElement(...).click();
assertEquals("Dashboard", "Dashboard");
}
}
Q2. How is TestNG different from JUnit?¶
TestNG and JUnit are both Java test frameworks, but TestNG offers built-in grouping, dependencies, data providers, parallel runs, and XML-driven suites that older JUnit lacked.
In plain words: JUnit is the classic unit-test tool; TestNG was built for larger end-to-end/automation suites.
| Feature | JUnit (4) | TestNG |
|---|---|---|
| Annotation style | @Before, @BeforeClass |
@BeforeMethod, @BeforeClass, @BeforeTest, @BeforeSuite |
| Grouping tests | No (native) | Yes, groups attribute |
| Dependencies | No | dependsOnMethods / dependsOnGroups |
| Data-driven | @Parameterized (verbose) |
@DataProvider (simple) |
| Parallel execution | Limited | Built-in via testng.xml |
| Suite config | Code / runners | testng.xml file |
Q3. What are the advantages of using TestNG?¶
TestNG advantages include flexible annotations, grouping, prioritization, dependency handling, data-driven testing, parallel execution, listeners, and detailed HTML/XML reports.
In plain words: it gives you fine control over what runs, when, with what data, and how results are reported — all without writing plumbing code.
@Test(priority = 1, groups = "regression", enabled = true, timeOut = 5000)
public void featureTest() { }
Q4. How do you install and configure TestNG in Eclipse?¶
You install TestNG in Eclipse via Help → Eclipse Marketplace (or Install New Software using the update site), then add the TestNG library/dependency to the project build path.
In plain words: install the plugin once, add the jar (or Maven dependency), and Eclipse gets a "Run as → TestNG Test" option.
<!-- Preferred: add via Maven pom.xml instead of manual jar -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
Q5. How do you run a TestNG test?¶
You run a TestNG test by right-clicking the class/method and choosing "Run As → TestNG Test", by running a testng.xml suite, or through Maven Surefire on the command line.
In plain words: run a single method from the IDE, or run a whole suite via the XML file.
<!-- Run this suite: Right-click testng.xml -> Run As -> TestNG Suite -->
<suite name="Suite1">
<test name="Test1">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
Q6. What are the commonly used TestNG annotations?¶
Common TestNG annotations are @Test, the @Before*/@After* configuration annotations (Suite/Test/Class/Method), @DataProvider, @Parameters, @Factory, and @Listeners.
In plain words: @Test marks test methods; the @Before/@After family runs setup/teardown at different scopes.
@BeforeSuite public void suiteSetup() {}
@BeforeTest public void testSetup() {}
@BeforeClass public void classSetup() {}
@BeforeMethod public void methodSetup() {}
@Test public void actualTest() {}
@AfterMethod public void methodTeardown() {}
@AfterClass public void classTeardown() {}
@AfterTest public void testTeardown() {}
@AfterSuite public void suiteTeardown() {}
Q7. What is the execution order of TestNG annotations?¶
The execution order is @BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite.
In plain words: it runs from the widest scope (suite) inward to the method, then unwinds back out.
// For 2 @Test methods, @BeforeMethod/@AfterMethod fire TWICE,
// while @BeforeClass/@AfterClass fire ONCE.
@BeforeSuite -> @BeforeTest -> @BeforeClass
-> @BeforeMethod -> @Test1 -> @AfterMethod
-> @BeforeMethod -> @Test2 -> @AfterMethod
-> @AfterClass -> @AfterTest -> @AfterSuite
Q8. What is the difference between @BeforeMethod and @BeforeClass?¶
@BeforeMethod runs before every @Test method in the class, while @BeforeClass runs only once before the first test method of the class.
In plain words: use @BeforeMethod for a fresh state per test (e.g., open a new page); use @BeforeClass for one-time setup (e.g., launch the browser).
| Aspect | @BeforeMethod |
@BeforeClass |
|---|---|---|
| Runs how often | Before EVERY @Test |
ONCE per class |
| Typical use | Reset data, new session per test | Launch driver, DB connect |
| Cost | Higher (repeated) | Lower (single) |
@BeforeClass public void launchBrowser() { /* runs once */ }
@BeforeMethod public void openLoginPage() { /* runs before each @Test */ }
Remember: @BeforeMethod = per test method (many times); @BeforeClass = per class (once). Confusing these is a classic interview trap.
Q9. What is the use of @DataProvider in TestNG?¶
@DataProvider supplies multiple sets of data to a test method, enabling data-driven testing where the same test runs once per row of an Object[][].
In plain words: it feeds a test different inputs so one method covers many scenarios.
@DataProvider(name = "logins")
public Object[][] loginData() {
return new Object[][] {
{"user1", "pass1"},
{"user2", "pass2"}
};
}
@Test(dataProvider = "logins")
public void login(String user, String pass) {
// runs twice, once per row
}
Q10. How do you use @Test(enabled = false)?¶
Setting enabled = false on @Test disables (skips) that test method so TestNG does not execute it.
In plain words: it is a permanent "off switch" for a test without deleting the code.
Q11. How do you group tests in TestNG?¶
You group tests with the groups attribute on @Test, then include/exclude those group names in testng.xml to run subsets like smoke or regression.
In plain words: tag tests so you can run "just the smoke tests" without listing each one.
<test name="SmokeRun">
<groups>
<run><include name="smoke"/></run>
</groups>
<classes><class name="tests.LoginTest"/></classes>
</test>
Q12. How do you run tests in parallel using TestNG?¶
You run tests in parallel by setting parallel="methods|classes|tests" and thread-count in the <suite> tag of testng.xml.
In plain words: TestNG spins up multiple threads so tests run at the same time, cutting execution time.
<suite name="ParallelSuite" parallel="methods" thread-count="4">
<test name="T1">
<classes><class name="tests.LoginTest"/></classes>
</test>
</suite>
Q13. What is the purpose of testng.xml file?¶
testng.xml is the suite configuration file that defines which classes/methods/groups run, sets parameters, listeners, and parallel/thread settings.
In plain words: it is the control panel for the whole run — you point TestNG at it and it knows exactly what to execute.
<suite name="RegressionSuite">
<parameter name="browser" value="chrome"/>
<test name="Regression">
<classes><class name="tests.CheckoutTest"/></classes>
</test>
</suite>
Q14. How do you create and configure testng.xml?¶
You create testng.xml at the project root (Eclipse can auto-generate it via "Convert to TestNG"), then add <suite>, <test>, <classes>, <groups>, <parameter>, and parallel attributes.
In plain words: right-click the test → TestNG → Convert to TestNG, then edit the generated XML to add whatever you need.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MySuite" parallel="tests" thread-count="2">
<listeners>
<listener class-name="listeners.ScreenshotListener"/>
</listeners>
<test name="ChromeTests">
<parameter name="browser" value="chrome"/>
<classes><class name="tests.LoginTest"/></classes>
</test>
</suite>
Q15. What is dependency testing in TestNG?¶
Dependency testing makes one test run only after another has passed, using dependsOnMethods or dependsOnGroups; if the dependency fails, dependents are skipped.
In plain words: "don't run checkout unless login succeeded first."
@Test
public void login() {}
@Test(dependsOnMethods = "login")
public void addToCart() {} // skipped if login fails
Q16. How do you make one test method dependent on another?¶
You use the dependsOnMethods attribute on @Test, passing the name(s) of the method(s) that must succeed first.
In plain words: name the prerequisite method and TestNG enforces the order automatically.
@Test
public void openApp() {}
@Test(dependsOnMethods = {"openApp"})
public void navigateToProfile() {}
Q17. What is the use of priority attribute in TestNG?¶
The priority attribute controls the order of @Test methods — a lower number runs first, and the default priority is 0.
In plain words: it lets you sequence tests since TestNG otherwise runs them alphabetically.
@Test(priority = 0) public void first() {}
@Test(priority = 1) public void second() {}
@Test(priority = 2) public void third() {}
Q18. How do you handle timeouts in TestNG?¶
You set the timeOut attribute (in milliseconds) on @Test; if the method exceeds it, TestNG marks it as failed.
In plain words: it guards against a test hanging forever — fail fast after N ms.
@Test(timeOut = 3000) // fails if it runs longer than 3 seconds
public void mustBeFast() {
// slow logic here
}
Q19. How do you skip tests in TestNG?¶
You skip tests statically with @Test(enabled = false) or at runtime by throwing a SkipException, which marks the test as skipped rather than failed.
In plain words: enabled=false is a permanent off switch; SkipException skips conditionally during execution (e.g., feature flag off).
import org.testng.SkipException;
@Test
public void featureTest() {
if (!featureEnabled()) {
throw new SkipException("Feature disabled, skipping");
}
// test logic
}
Q20. What is the difference between assert and soft assert in TestNG?¶
A hard Assert stops the test immediately on the first failure, while a SoftAssert collects all failures and reports them only when assertAll() is called.
In plain words: hard assert = stop at first problem; soft assert = keep checking, report everything at the end.
| Aspect | Hard Assert (Assert) |
Soft Assert (SoftAssert) |
|---|---|---|
| On failure | Aborts test right away | Continues execution |
| Reporting | Immediate | Deferred until assertAll() |
Needs assertAll() |
No | Yes (else failures ignored) |
| Use when | One critical check | Verify many fields on a page |
// Hard assert
Assert.assertEquals(actual, "expected"); // stops here if it fails
// Soft assert
SoftAssert sa = new SoftAssert();
sa.assertEquals(title, "Home");
sa.assertTrue(isLoggedIn);
sa.assertAll(); // reports all collected failures
Remember: With SoftAssert you MUST call assertAll() at the end — otherwise failures are silently swallowed and the test "passes."
Q21. How do you implement parameterization in TestNG?¶
You parameterize either with @Parameters (values injected from testng.xml) or with @DataProvider (multiple rows returned from a method).
In plain words: use @Parameters for a few config values (like browser); use @DataProvider for many data rows.
@Parameters({"browser"})
@Test
public void run(String browser) {
// browser comes from testng.xml <parameter>
}
Q22. What is a listener in TestNG?¶
A listener is an interface (like ITestListener) whose callback methods TestNG invokes on test events — start, success, failure, skip — letting you hook custom behavior such as logging or screenshots.
In plain words: it "listens" to test events and lets you react, e.g., capture a screenshot when a test fails.
import org.testng.ITestListener;
import org.testng.ITestResult;
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
// capture screenshot on failure
}
}
Q23. How do you use listeners in TestNG?¶
You attach a listener either with the @Listeners annotation on the test class or by declaring it in the <listeners> section of testng.xml.
In plain words: point TestNG at your listener class one of two ways, and it fires automatically.
Q24. What is the difference between @BeforeSuite and @BeforeTest?¶
@BeforeSuite runs once before the entire suite (all <test> tags), while @BeforeTest runs once before each <test> tag defined in testng.xml.
In plain words: suite is the outermost scope; a <test> is a section inside the suite, so @BeforeTest can run several times if the XML has several <test> tags.
| Aspect | @BeforeSuite |
@BeforeTest |
|---|---|---|
| Scope | Whole suite | Each <test> in XML |
| Frequency | Once per suite | Once per <test> tag |
| Typical use | Global config, start grid | Per-test-block browser/env setup |
<suite name="S">
<test name="A">...</test> <!-- @BeforeTest fires here -->
<test name="B">...</test> <!-- and again here -->
</suite> <!-- @BeforeSuite fires once for the whole S -->
Q25. How do you generate reports in TestNG?¶
TestNG auto-generates default HTML and XML reports (index.html, emailable-report.html, testng-results.xml) in the test-output folder after every run; you can also plug in custom reporters like ExtentReports.
In plain words: reports appear automatically in test-output/; for prettier ones, add a reporting library.
<!-- Add ExtentReports/other reporter as a listener -->
<listeners>
<listener class-name="reporters.ExtentReportListener"/>
</listeners>
Q26. How can you run tests from the command line using TestNG?¶
You run TestNG from the command line either via java org.testng.TestNG testng.xml with the classpath set, or through Maven with mvn test.
In plain words: give TestNG the classpath and the XML file, or just let Maven drive it.
# Direct TestNG runner
java -cp "libs/*:bin" org.testng.TestNG testng.xml
# Via Maven (uses Surefire)
mvn clean test
Q27. How do you handle exceptions in TestNG tests?¶
You handle exceptions with normal try/catch, or declare an expected exception with @Test(expectedExceptions = SomeException.class) so the test passes only when that exception is thrown.
In plain words: either catch it yourself, or tell TestNG "this test is supposed to throw this exception."
@Test(expectedExceptions = ArithmeticException.class)
public void divideByZero() {
int x = 5 / 0; // test passes because this exception is expected
}
Q28. What are the different types of assertions in TestNG?¶
TestNG offers hard assertions via the static Assert class (assertEquals, assertTrue, assertFalse, assertNull, assertNotNull, fail) and soft assertions via SoftAssert that defer reporting to assertAll().
In plain words: many assert methods to compare values/conditions, in both hard (stop-on-fail) and soft (collect-all) flavors.
Assert.assertEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertNotNull(object);
Assert.fail("forced failure");
SoftAssert sa = new SoftAssert();
sa.assertFalse(isError);
sa.assertAll();
Q29. Can you explain how TestNG integrates with Maven?¶
TestNG integrates with Maven through the maven-surefire-plugin, which runs your testng.xml suite files (declared under <suiteXmlFiles>) during the test phase, with the TestNG dependency in the pom.
In plain words: add TestNG as a dependency, tell Surefire which XML suites to run, and mvn test executes them.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
Q30. How do you debug TestNG tests?¶
You debug TestNG tests by setting breakpoints and choosing "Debug As → TestNG Test" in the IDE, using logs/Reporter.log, listeners for failure screenshots, and inspecting the test-output reports.
In plain words: run it in debug mode with breakpoints, add logging, and lean on listeners/reports to see where it broke.