TestNG interview questions and answers for automation engineers

TestNG interview questions test whether you can organize a Java test suite that stays fast and trustworthy as it grows: the order of setup and teardown annotations, suites and groups in testng.xml, data providers, dependencies, parallel execution and listeners. Freshers get the annotation order and assertions; experienced candidates get thread safety in parallel Selenium runs, retry policy, flaky test triage and how the suite plugs into Maven or Gradle in CI.

By Published 8 min read

Where TestNG questions come up

TestNG is a Java test runner that many UI and API automation teams pair with Selenium, REST Assured or Appium. It shows up in interviews for automation tester, SDET, QA automation lead and Java developer roles where the team runs integration suites. A typical round starts with annotations and assertions, moves to a whiteboard or screen-share of a testng.xml file, and ends with a scenario about a suite that is flaky or too slow. If the job also lists browser work, expect overlap with Selenium interview questions; if the team is weighing runners, the JUnit interview questions page covers the other side of that comparison.

  1. Warm-upWhy TestNG, the annotation order, and what each @Test attribute does.
  2. Suite designReading or writing a testng.xml with groups, parameters and parallel settings.
  3. Framework internalsListeners, retry, data-driven tests and how your framework reports results.
  4. ScenarioA failing or flaky suite in CI, and how you would find and fix the cause.

TestNG fundamentals questions

Early-round questions on annotations and assertions
QuestionWhat it testsWhat a strong answer shows
List the configuration annotations from widest to narrowest scope.Lifecycle@BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, then the @Test method, then the matching @After annotations on the way out. @BeforeGroups is the odd one: it fires just before the first method of that group runs, so in practice it usually comes after @BeforeClass. Note that @BeforeTest refers to a <test> tag in testng.xml, not to each test method.
What is the most common mix-up with @BeforeTest?PrecisionPeople expect it to run before every test method. It runs once before each <test> block in the suite file. Per-method setup belongs in @BeforeMethod.
Name five attributes of @Test.Tool fluencygroups, priority, dependsOnMethods, enabled, timeOut, invocationCount, dataProvider, expectedExceptions, alwaysRun and description. Mention one you have actually used and why.
Hard assert versus soft assert?AssertionsA hard assert (Assert.assertEquals) stops the method at the first failure. SoftAssert collects failures and reports them all when you call assertAll(). Forgetting assertAll() makes every soft check pass silently.
What order do TestNG's assertEquals arguments take?DetailActual first, expected second. JUnit's classic assertEquals is the other way round, so mixing them produces misleading failure messages.
How do you test that a method throws?Negative testsUse expectedExceptions on @Test, optionally with expectedExceptionsMessageRegExp, or catch it explicitly with Assert.assertThrows when you need to inspect the exception.
How do you skip a test temporarily?HousekeepingSet enabled = false, or throw SkipException from inside the test for a conditional skip. Either way, leave a reason and a ticket so it does not stay disabled for a year.
What does timeOut do?StabilityIt fails a test that runs longer than the given number of milliseconds, which stops one hung call from freezing the whole suite.
Where do TestNG's default reports go?ReportingInto a test-output folder by default, with an HTML index, an emailable report and an XML results file. Most teams add a listener or a reporting library on top.
Why choose TestNG over JUnit?JudgementHistorically for suite XML files, groups, dependencies and built-in parallel runs. JUnit 5 closed much of that gap, so a good answer names the features your team actually uses rather than declaring a winner.
Early-round questions on annotations and assertions. Scroll sideways on a small screen.

Intermediate: suites, groups and data

  • Walk me through a testng.xml file. A <suite> holds one or more <test> blocks; each test lists classes, packages or methods, and can include or exclude groups and set parameters. The suite level sets parallel mode, thread count and listeners.
  • How do groups help a team? Tag tests as smoke, regression or slow, then run only the smoke group on every pull request and the full set at night. Groups can also be pulled in from the command line or the build tool, so one suite file serves several pipelines.
  • Priority versus dependsOnMethods? Priority only orders tests: lower numbers run first and the default is zero. A dependency changes outcomes: if the method it depends on fails, the dependent test is skipped rather than run. Use dependencies sparingly, because they make tests impossible to run alone.
  • What does alwaysRun = true change? On a dependent test it runs even if the dependency failed; on an @After method it runs even if earlier configuration failed or the test sits in an excluded group. It is how cleanup survives a broken run.
  • How does @DataProvider work? A method annotated with @DataProvider returns rows, usually as Object[][] or an Iterator of Object[], and each row becomes one invocation of the test. It can live in another class through dataProviderClass, and parallel = true runs the rows concurrently.
  • @DataProvider versus @Parameters? @Parameters reads single values from testng.xml, such as browser or environment, with @Optional supplying a default. A data provider feeds many rows from code, CSV, JSON or a database. They solve different problems and often appear together.
  • What is @Factory for? It builds test class instances at run time, for example one instance per user role, each with its own fields, so the same tests run against different configurations.
  • How do you rerun only the tests that failed? After a run, TestNG writes a testng-failed.xml suite listing the failures. Running it repeats just those, which is handy locally. In CI most teams prefer a retry analyzer with a strict limit and visible reporting.
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;

public class DiscountTest {

    @DataProvider(name = "carts")
    public Object[][] carts() {
        return new Object[][] {
            {"STANDARD", 100.0, 100.0},
            {"MEMBER", 100.0, 90.0},
            {"EMPLOYEE", 100.0, 80.0},
        };
    }

    @BeforeMethod(alwaysRun = true)
    public void resetPricingCache() {
        PricingCache.clear();
    }

    @Test(dataProvider = "carts", groups = {"smoke", "pricing"})
    public void appliesTierDiscount(String tier, double subtotal, double expected) {
        double total = Pricing.total(tier, subtotal);
        SoftAssert soft = new SoftAssert();
        soft.assertEquals(total, expected, "total for " + tier);
        soft.assertTrue(total <= subtotal, "discount never raises the price");
        soft.assertAll();   // without this line, failures are never reported
    }
}
A short data-driven test with groups and a soft assertion. Not executed here (no TestNG jar on this machine); shown for the structure interviewers ask about.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="checkout" parallel="classes" thread-count="4">
  <listeners>
    <listener class-name="com.example.qa.ScreenshotOnFailure"/>
  </listeners>
  <test name="smoke-chrome">
    <parameter name="browser" value="chrome"/>
    <groups>
      <run>
        <include name="smoke"/>
      </run>
    </groups>
    <packages>
      <package name="com.example.qa.checkout"/>
    </packages>
  </test>
</suite>
A suite file that runs only the smoke group, with classes in parallel. Not executed here.

Advanced: parallel runs, listeners and retries

Questions for experienced automation engineers
QuestionWhat it testsWhat a strong answer shows
What are the parallel modes in testng.xml?Concurrencymethods, classes, tests and instances, each with a thread-count. The choice decides what shares a thread: with classes, all methods of one class stay on one thread, which is often the safest start for UI suites.
Your Selenium tests pass alone but fail in parallel. Why?Thread safetyA static or shared WebDriver, shared page objects or shared test data. Keep the driver in a ThreadLocal created in @BeforeMethod and quit in @AfterMethod with alwaysRun, and give each test its own data.
Which listeners have you written?ExtensibilityITestListener for onTestFailure screenshots and logs, ISuiteListener for suite-wide setup, IReporter for a custom report, IInvokedMethodListener for timing. Register them in testng.xml, with @Listeners, or through the service loader.
How does IRetryAnalyzer work, and what is the risk?Flakiness policyIts retry method returns true while a failed test should run again, up to a limit you set. Applied to every test through an annotation transformer it is easy to hide real defects, so cap retries, report retried passes separately and fix the root cause.
What is IAnnotationTransformer used for?InternalsChanging annotation values at run time, such as attaching a retry analyzer to every @Test or disabling tests by a rule, without editing each method.
How does TestNG inject objects into test methods?Native injectionConfiguration and test methods can declare parameters such as ITestContext, ITestResult or java.lang.reflect.Method, and TestNG passes them in. That is how a @BeforeMethod reads the current test's name for logging.
How do you share state between tests safely?DesignPrefer not to. If needed, use ITestContext attributes scoped to the <test> block, never static fields in parallel runs, and document the dependency.
How do you run TestNG from Maven or Gradle?CIMaven Surefire picks up the suite through suiteXmlFiles or runs annotated classes directly; Gradle uses useTestNG() with groups to include or exclude. Pass groups or the suite file as a build property so pipelines differ only in arguments.
Questions for experienced automation engineers. Scroll sideways on a small screen.

Senior and scenario questions

  • The nightly regression suite went from forty minutes to three hours. What do you look at? Per-test timing from a listener or the XML results, new fixed sleeps, tests that each launch a fresh browser and log in, a data provider that grew, and whether parallel settings changed. Fix the top offenders first, then raise the thread count only after the tests are independent.
  • Ten percent of runs fail on different tests each time. Classic flakiness: race conditions with the app, shared data, order dependence or environment instability. Rerun the failures alone, compare logs and screenshots with passing runs, and quarantine into a separate group while fixing, with an owner and a date.
  • A test only passes when run after another test. It depends on state the first one leaves behind. Make the setup explicit in @BeforeMethod or a fixture builder, and run the suite in a shuffled or isolated order to find more of these.
  • Product asks for a quick smoke pack on every deploy. Tag a small set of business-critical journeys with a smoke group, run them against the deployed environment with a parameterized base URL, and fail the pipeline fast with a readable report link.
  • How would you structure a TestNG framework for a new team? Page objects or API clients in their own module, test classes thin and readable, data in providers backed by files, configuration through parameters or environment variables, listeners for screenshots and logs, and one suite file per pipeline purpose.
  • When would you not use dependsOnMethods? Almost always for UI journeys. A login failure should fail one clear test, and every later test should log in through a fast API call in its own setup, so it can still run and report on its own.
  • Should the team migrate from TestNG to JUnit 5? Only with a reason: existing suites, team skill, plugin support and parallel needs. Migration costs time that could fix flaky tests; a sound answer weighs that rather than following fashion.

Fictional example

Answering "Your parallel UI suite fails randomly. Talk me through it"
Interviewer
We moved our 300 Selenium tests to parallel="methods" with eight threads, and now about a dozen fail each night, never the same ones.
Candidate
Random failures that started with parallel runs point first at shared state. I would check how the driver is held. If it is a static field, eight threads are steering the same browsers, so I would move it into a ThreadLocal created in @BeforeMethod and quit in @AfterMethod with alwaysRun. Next I would look for shared test accounts: two tests editing the same cart will collide, so each test should create or reserve its own data. Then I would drop to parallel="classes" as a safer middle step while those fixes land, and use a failure listener to attach a screenshot and the browser log to each failed result so we can compare failures quickly. Only after that would I consider a retry analyzer, capped at one retry and reported separately, so we keep seeing which tests are unstable.

A five-day TestNG practice plan

One focus per day, each ending with something you can show
DayFocusProof you are ready
1Annotation order and @Test attributesWrite the lifecycle order from memory and explain @BeforeTest correctly.
2testng.xml, groups and parametersHand-write a suite that runs smoke tests on two browsers through parameters.
3Data providers and soft assertsConvert a copy-pasted test into one data-driven test with readable failure messages.
4Parallel runs and listenersExplain ThreadLocal drivers and sketch a screenshot-on-failure listener.
5ScenariosTalk through a flaky suite and a slow suite out loud, in under three minutes each.
One focus per day, each ending with something you can show. Scroll sideways on a small screen.

Testers who work in commercial tools rather than code should also skim Tosca interview questions and UFT interview questions, since some automation roles ask how a TestNG suite would sit beside those tools in one pipeline.

Natively is an AI interview assistant for Mac and Windows that suits rehearsing these rounds. Run a mock where a friend reads you a broken testng.xml, and Natively transcribes the session so you can check afterward whether you explained @BeforeTest and parallel modes precisely. During practice it can read a stack trace or suite file from a screenshot and suggest follow-up questions, and with Pro or the free trial it tailors suggestions to the résumé and job description you add. The transcript and notes stay available for review.

Questions people ask

What TestNG questions are asked in automation testing interviews?

The order of configuration annotations, @Test attributes, hard versus soft asserts, testng.xml with groups and parameters, data providers, priority versus dependencies, parallel modes, listeners and retry analyzers.

What is the difference between @BeforeTest and @BeforeMethod in TestNG?

@BeforeTest runs once before each <test> block in testng.xml. @BeforeMethod runs before every test method, which is where per-test setup such as a fresh browser belongs.

How do you run TestNG tests in parallel safely?

Set the parallel mode and thread-count in testng.xml, keep the WebDriver in a ThreadLocal, give each test its own data, and quit drivers in an @AfterMethod with alwaysRun set to true.

Is TestNG better than JUnit for interviews?

Neither is better in general. Know why your team chose TestNG, such as suite files, groups or dependencies, and how JUnit 5 handles the same needs.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP