Beginner Questions
20 questions
1. What is TestNG and why is it used in automation testing?
TestNG, which stands for Test Next Generation, is a Java testing framework designed to make test execution more flexible and scalable than older unit-test-focused frameworks. It is widely used in automation projects because it supports groups, dependencies, data-driven testing, parallel execution, and structured setup or teardown behavior.
In Selenium and broader automation frameworks, TestNG is valued not just as a test runner, but as the layer that organizes execution flow. It helps teams manage large suites, separate smoke and regression coverage, and integrate reporting and CI behavior in a cleaner way. In simple terms, it helps turn individual automated scripts into a controlled and maintainable testing system.
2. Explain the TestNG lifecycle with annotations and their execution order.
TestNG controls the test lifecycle through annotations such as @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, @AfterMethod, @AfterClass, @AfterTest, and @AfterSuite. These define when environment setup begins, when class-level resources are prepared, when each individual test starts, and when cleanup happens.
The usual execution flow is suite-level setup first, then test-level setup, then class-level setup, then method-level setup before each @Test, followed by matching teardown in reverse order. This structure is important because it keeps initialization predictable and prevents resource leaks in larger frameworks.
3. How does TestNG differ from JUnit?
TestNG and JUnit are both Java testing frameworks, but TestNG was designed with broader automation needs in mind. TestNG supports built-in grouping, dependencies, XML-based suite control, richer parameterization, and stronger parallel execution support without requiring as much extra setup.
JUnit is often simpler and widely used for unit testing, while TestNG is more common in larger Selenium-style automation suites where execution control matters. The practical difference is that TestNG gives teams more orchestration features out of the box, especially for enterprise automation workflows.
| Aspect | TestNG | JUnit |
|---|---|---|
| Primary Strength | Flexible test orchestration | Simple and popular unit testing |
| Dependencies | Built-in support | More limited by default |
| Grouping | Strong built-in groups | Less central in the framework model |
| Parallel Execution | Better suited for suite-scale runs | Possible, but less orchestration-focused |
4. What are the main annotations in TestNG?
The main annotations in TestNG include @Test, @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod, @DataProvider, @Parameters, @Factory, and @Listeners. Each annotation controls a different part of execution or data flow.
These annotations matter because they define framework structure, not just syntax. Good TestNG usage depends on placing setup, teardown, test data, and configuration at the right lifecycle level so the suite stays readable and predictable as it grows. In practice, clear annotation design reduces duplication and makes it much easier to understand what happens before, during, and after each test.
5. What is a TestNG suite and how is it configured?
A TestNG suite is a collection of tests configured together, usually through a testng.xml file. The suite file defines which classes to run, how tests are grouped, whether execution should be parallel, which parameters should be passed, and which listeners or included groups should apply.
This is one of TestNG’s biggest strengths because it separates execution strategy from test code. Teams can run the same code differently in smoke, regression, nightly, or browser-specific pipelines just by changing suite configuration.
6. How do you install and set up TestNG in Eclipse or IntelliJ?
TestNG is usually set up by adding the framework dependency through Maven or Gradle, then enabling IDE integration so tests can be run directly from the editor. In Eclipse, teams often install the TestNG plugin if needed. In IntelliJ, TestNG support is usually available directly once the dependency is present.
The important part is not only installation, but making sure the project can run suites consistently through both the IDE and build tool. That keeps local execution aligned with CI and avoids environment-specific behavior. A good setup is one where the same suite can run from the editor, from Maven or Gradle, and inside the pipeline without any special local adjustments.
7. What is testng.xml and what are its key elements?
The testng.xml file is the main suite configuration file in TestNG. It defines the suite structure and can include elements such as suite, test, classes, class, methods, groups, parameter, and parallel execution settings.
Its purpose is to control execution without hardcoding all behavior inside Java classes. That makes it useful for selecting subsets of tests, passing environment values, controlling threads, and keeping regression or smoke execution strategies separate from the test implementation itself. It becomes especially valuable when the same codebase needs different execution modes such as smoke, full regression, cross-browser runs, or environment-specific validation.
8. What is the difference between @Test priority and dependsOnMethods?
The priority attribute gives TestNG a preferred ordering among tests, while dependsOnMethods defines an actual dependency relationship. Priority influences sequence, but the tests are still conceptually independent. Dependencies mean one test should only run if another one succeeds.
This difference matters because ordering and dependency are not the same idea. Priority is useful for predictable flow when needed, but dependencies should be used when later behavior truly relies on an earlier successful step.
| Aspect | priority | dependsOnMethods |
|---|---|---|
| Purpose | Controls preferred execution order | Defines logical dependency |
| Failure Impact | Does not automatically skip later tests | Can skip dependent tests on failure |
| Best Use | Ordering convenience | Workflow dependency |
9. How do you ignore a test in TestNG?
A test can be ignored by setting enabled = false on the @Test annotation or by using mechanisms such as excluding groups from suite configuration. Some teams also use annotation-based patterns or temporary suite exclusion while debugging or isolating unstable areas.
Ignored tests should be used deliberately and tracked carefully. Disabling tests can be useful during controlled maintenance, but if it becomes a habit, the suite can quietly lose coverage without people noticing. In mature automation setups, disabled tests are reviewed regularly so they do not become permanent blind spots in regression coverage.
10. Explain hard assertions vs soft assertions in TestNG.
A hard assertion fails the test immediately when the validation does not match the expectation. A soft assertion records the failure but allows execution to continue until all validations are collected, after which the failures are reported together.
Hard assertions are useful when the rest of the test no longer makes sense after a failure, such as a failed login. Soft assertions are more useful when validating many independent UI states in one flow and you want a broader picture of what broke.
| Aspect | Hard Assertion | Soft Assertion |
|---|---|---|
| Failure Behavior | Stops immediately | Continues and collects failures |
| Best Fit | Critical prerequisite validation | Multiple independent checks |
| Debugging Style | Fast fail | Broader evidence from one run |
11. What is @DataProvider?
The @DataProvider annotation marks a method that supplies test data to one or more @Test methods. The provider typically returns an Object[][] or an iterator-based structure so the same test logic can run multiple times with different inputs.
This makes TestNG a strong fit for data-driven testing. Instead of duplicating test methods for different users, roles, or input combinations, teams can centralize the data and keep the workflow logic in one place.
12. How do you run tests in parallel in TestNG?
Parallel execution in TestNG is usually configured through testng.xml by setting the parallel mode to values such as methods, classes, or tests, along with a thread-count. In some cases, annotation-level controls such as threadPoolSize can also be used.
The critical part is not just enabling threads, but making the framework safe for parallel runs. Drivers, test data, and shared state must be isolated; otherwise, parallelism makes failures faster but not more reliable.
13. What is the purpose of @BeforeMethod and @AfterMethod?
The @BeforeMethod annotation runs before every test method, and @AfterMethod runs after every test method. They are commonly used for per-test setup and cleanup, such as opening a browser session, preparing mock data, resetting state, or capturing failure artifacts.
These hooks are valuable because they create consistent boundaries between tests. When used well, they reduce leakage between scenarios and make each test more independent and easier to debug.
14. How do you pass parameters from testng.xml?
Parameters can be passed from testng.xml using the parameter element and consumed in Java through the @Parameters annotation. This allows values such as environment, browser, base URL, or credentials profile names to be injected without hardcoding them in the test class.
It is useful for configuration-oriented values that should vary across suites or environments. This keeps the execution setup flexible while leaving the underlying test logic unchanged.
15. What are TestNG groups and how do you include or exclude them?
Groups in TestNG allow tests to be tagged under logical labels such as smoke, regression, api, or ui. These groups can then be included or excluded in testng.xml so only the intended subset runs in a given pipeline or local session.
This is a powerful organization tool because large suites rarely need every test on every run. Groups help teams create meaningful execution slices without duplicating suite definitions or editing test code repeatedly.
16. What is the difference between @Parameters and @DataProvider?
@Parameters usually injects configuration values from testng.xml, while @DataProvider supplies test data programmatically for repeated execution. The former is better for environment-level inputs, and the latter is better for multiple data rows or many test iterations.
They solve different problems even though both pass values into tests. One is configuration-driven, and the other is data-driven. @Parameters works best when the suite decides the value, while @DataProvider works best when the same test needs to run repeatedly with many inputs.
| Aspect | @Parameters | @DataProvider |
|---|---|---|
| Source | Usually testng.xml | Java method returning data |
| Best Fit | Configuration values | Repeated test datasets |
| Execution Style | Single injected run context | Multiple test invocations |
17. How do you generate reports in TestNG?
TestNG generates default HTML and XML reports after execution, and these can be consumed directly or enhanced through plugins and reporting tools. Many teams also attach listeners or integrate frameworks such as Allure or ExtentReports for richer output.
Reporting matters because large suites need more than pass or fail status. Good reports should help explain what ran, what failed, why it failed, and what evidence is available for diagnosis. Strong reporting makes debugging faster by tying failures to screenshots, logs, timings, and environment details instead of showing only summary counts.
18. What is the role of ITestResult?
ITestResult provides execution details about an individual test method, such as status, start and end time, parameters, exceptions, and associated method metadata. It is commonly used inside listeners, retries, logging hooks, and reporting integrations.
This makes it useful when the framework needs to react differently to success, failure, skip, or retry cases. It is one of the key interfaces for turning raw execution into structured diagnostics. For example, a failure listener can read ITestResult, capture the exception, attach a screenshot, record the browser name, and publish all of that into a report automatically.
19. How do you run TestNG from the command line?
TestNG can be run from the command line through build tools such as Maven or Gradle, or directly through Java execution when the classpath and suite file are set up correctly. In practice, most teams rely on Maven Surefire, Gradle test tasks, or CI commands rather than manual raw Java execution.
The important part is repeatability. Command-line execution should behave the same way as CI so failures can be reproduced locally using the same suite settings, groups, parameters, and reporting behavior that the pipeline uses.
20. What is the basic structure of a TestNG test class?
A basic TestNG class usually contains setup annotations such as @BeforeMethod or @BeforeClass, one or more @Test methods, and matching teardown annotations such as @AfterMethod or @AfterClass. It may also include helper methods, data providers, or assertions.
The structure should reflect test intent clearly: setup prepares state, test methods validate behavior, and teardown restores or releases resources. That separation becomes especially important as the framework grows. Even in small projects, this structure helps keep business validation separate from environment setup and cleanup logic.