4_TestNG Interview Questions and Answers
4_TestNG Interview Questions and Answers
Inspired by JUnit, TestNG was created by Cedric Beust in 2004. TestNG is a free and open-source Java
test automation framework. It is based on the same principles as JUnit and NUnit. TestNG's advanced
and useful features make it a more robust framework than its competitors. Such as annotations being
easier to use, HTML reports for implementations, and enabling you to group test cases.
TestNG's NG stands for 'Next Generation.' It was developed by Cedric Beust and is increasingly utilized
by developers and testers in test case generation due to the ease of use of numerous annotations,
grouping, dependence, priority, and parametrization capabilities.
Method 1:
In the first method, you run TestNG scripts from the command line by specifying the TestNG JAR file and
the path to your test class file in the java command. Here is the code snippet for a better understanding
Replace testng.jar with the name of the TestNG JAR file, path/to/your/test/class with the path to the file
containing your test class, and com.testng.TestClass with the fully qualified name of your test class.
Method 2:
Include the TestNG library in the build path of your project. To do so, download the TestNG JAR file and
add it to the classpath of your project or by using a build tool such as Maven or Gradle.
Create a Java class file for your TestNG test cases. This class's methods that include test code should
have the @Test annotation.
On the Project Explorer view, right-click on the test class file and choose "Run As" > "TestNG Test" (or
use the keyboard shortcut, usually Ctrl+Shift+F10).
TestNG will run your class's test methods and provide a report with the results of each test case.
TestNG is built on the same foundation as JUnit and NUnit. TestNG is a more robust framework than its
competitors due to its advanced and valuable capabilities. Some of the major benefits of TestNG
include:
TestNG allows you to conveniently group test cases, which JUnit does not allow.
TestNG includes three more levels: @Before/After suite, @Before/AfterTest, and Before/AfterGroup.
No classes are extended by TestNG. The TestNG framework allows you to define test scenarios that are
independent of one another.
TestNG has extensive reporting options, including HTML and XML reports with detailed information
about test execution results. This makes identifying test failures and diagnosing problems much easier
There are no constraints available in TestNG, such as @beforeclass and @afterclass, which are present
in Junit.
4. What is the difference between a TestNG test and a TestNG test suite?
The major difference between the TestNG test and the TestNG test suite is aTestNG test is a single Java
class with one or more test methods annotated with the @Test annotation. In contrast, a TestNG test
suite is an XML file that contains one or more TestNG test definitions.
Here is some other difference between TestNG and TestNG test suites:
A TestNG test is used to test a specific application functionality or feature, whereas a TestNG test suite is
used to bundle related tests together and run them as a unified unit.
A TestNG test runs using a test runner, such as the TestNG plugin for Eclipse or the testng.xml file. While
the testng.xml file is used to run a TestNG test suite.
TestNG is one of the leading automation testing frameworks, and it has several advantages over JUnit.
Here is a list of advantages that TestNG has over JUnit:
TestNG allows you to conveniently aggregate test cases, which JUnit does not allow.
TestNG includes three more levels: @Before/After suite, @Before/AfterTest, and Before/AfterGroup.
It does not add any new classes. As a result, the TestNG framework allows you to define test cases that
are independent of one another.
Only the TestNG framework allows for parallel execution of test cases, i.e., running many test cases
simultaneously.
7. What are the basic steps required in writing the TestNG test?
The following are the basic steps involved in creating a TestNG test:
Add the TestNG library to your project's classpath after downloading it.
Make a Java class and annotate it with @Test or another TestNG annotation; in the annotated method,
write the test code.
Execute the test using TestNG's test runner, which can be invoked from an IDE or the command line.
Suite: The highest level of organization in TestNG is a suite. It is a set of one or more tests that can be
run concurrently. A suite may include several tests, configurations, and other elements such as listeners,
parameters, and groups.
Test: A test is a collection of related test cases that can be executed concurrently. A test may contain
one or more classes and various parameters and configurations.
Class: A class is a Java class that contains one or more test methods. Test methods are marked with
@Test and run as part of a test. Other methods for setting up or tearing down the test environment can
also be found in a class.
9. How will you execute methods or test cases in TestNG in a different order/your order?
We can control the order of method execution in TestNG by using various attributes and annotations.
Here are some examples of how to execute methods or test cases in a specific order:
10. Define the correct order of tags in the TestNG XML file.
The following is the correct order to run the TestNG suite from the XML file:
<!DOCTYPE suite SYSTEM "https://www.lambdatest.com/">
<suite name="MyTestSuite">
<listeners>
</listeners>
<classes>
<class name="com.example.tests.MyTestClass">
<methods>
</methods>
<groups>
<run>
</run>
<exclude>
</exclude>
</groups>
<parameters>
</parameters>
</class>
</classes>
</test>
<packages>
<method-selector>
</method-selector>
<suite-files>
</suite-files>
</suite>
Please remember that this is just an example, and the actual tags used may vary depending on your
project's specific testing requirements and configurations.
The XML file is used in TestNG to configure and customize the test execution process. It contains a
number of elements and attributes that define the suite, test cases, test methods, groups, listeners, and
other settings that govern how the tests are run.
Here are some reasons why we should create an XML file in TestNG:
The XML file allows you to configure the test suite, set parameters, and tailor the test execution process
to your specific needs.
You can specify the priority of test methods, and TestNG will execute them in the order you specify.
You can group the test methods based on their functionalities and execute only the necessary group of
methods.
The test parameters can be specified in the XML file, and TestNG will pass those parameters to the test
methods at runtime.
It allows you to specify which test methods can be executed concurrently, and TestNG will execute them
concurrently, saving you time.
12. Write the code snipped for passing values 1 and 2 to the parameters val1 and val2 through the XML
file.
Here's an example of code that shows how to use the XML file to pass values 1 and 2 to the parameters
"val1" and "val2":
<suite name="MyTestSuite">
<test name="MyTest">
<parameter name="val1" value="1" />
<classes>
</classes>
</test>
</suite>
// Java code
@Test
The "<parameter>" tag is used in this example to specify the values for the "val1" and "val2" parameters
in the TestNG XML file. The Java code then declares these parameters with the "@Parameter"
annotation and passes their values to the "testMethod()" method.
13. Can you arrange the below testng.xml tags from parent to child?
<test>
<suite>
<class>
<methods>
<classes>
<suite>
<test>
<classes>
<class>
<methods>
14. Can we use regular expressions in TestNG groups? Write a demo XML file for the same.
TestNG supports groups of regular expressions, which might be useful for selecting a subset of tests
based on a given pattern.
Here's an example of a TestNG XML file that groups test using regular expressions:
<groups>
<run>
<include name=".*smoke.*"/>
</run>
</groups>
<classes>
<class name="com.example.tests.Test1"/>
<class name="com.example.tests.Test2"/>
<class name="com.example.tests.Test3"/>
</classes>
</test>
</suite>
The regular phrase ".smoke." is used in this example to pick tests with the term "smoke" in their group
name. The include tag specifies the regular expression, and the run tag specifies that only tests that
match the regular expression should be executed.
This TestNG XML file will run all tests in the classes com.example.tests.Test1, com.example.tests.Test2,
and com.example.tests.Test3 if they are part of a group that fits the regular expression ".smoke."
15. What is the use of the preserve-order attribute in the TestNG XML file?
The preserve-order attribute in the TestNG XML file specifies whether the test methods in a test class
should be executed in the order defined in the Java code. If the preserve-order property is set to true,
TestNG will keep the order of test methods as defined in the Java code. TestNG may run the test
methods in any order if preserve-order="false."
16. How to Integrate TestNG XML with Maven?
Add the TestNG dependency to your Maven pom.xml file, create a TestNG XML file and add your test
classes and configurations, add the maven-surefire-plugin to the build section of your pom.xml file, and
run your Maven tests using the test command to integrate TestNG XML with Maven.
You can use the below example as a reference to add the maven-surefire-plugin to the build section of
your Maven pom.xml file and specify the TestNG XML file to use.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
17. How to pass the parameter in the test case through the testng.xml file?
You can use the parameter tag within the test tag to pass parameters in the test case via the TestNG
XML file. First, You need to specify the parameter name and value within the tag. These parameters can
be accessed in the test case by using the @Parameters annotation in the method signature, as shown
below:
@Test
@Parameters({"username", "password"})
}
The myTestMethod method in the preceding example is annotated with the @Parameters annotation,
which specifies the parameter names username and password. The method code then uses these
parameters to run the test.
Using a text editor or an IDE, create a new file with the.xml extension.
To define the DTD, use the <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> tag, and the <!
—Test suite—> tag to define the test suite.
Define the test tags within the test suite with the necessary attributes such as name and verbose. And
within test tags, define classes or methods that must be executed within each test tag using the class
and method tags, respectively.
<suite name="MyTestSuite">
<test name="MyTest">
<classes>
<class name="com.example.MyTestClass"/>
</classes>
</test>
</suite>
You should check out our blog on how to create TestNG XML file to get a better insight.
19. How to write regular expressions In testng.xml file to search @Test methods containing the “smoke”
keyword.
You can use the <test> tags include the attribute. Here is an example of code that shows how to write a
regular expression in a TestNG XML file:
<classes>
</classes>
<methods>
<include name=".*smoke.*"/>
</methods>
</test>
</suite>
20. What are the types of annotations used in TestNG (In the sequence of execution/hierarchy)?
Annotations in TestNG are used to specify the behavior of test methods. The annotations are carried out
in a specific order and hierarchy. The following are the types of annotations used in TestNG in the
execution sequence/hierarchy:
Before Suite
Before Test
Before Class
Before Method
Test 1
After Method
Before Method
Test 2
After Method
After Class
After Test
After Suite
@BeforeSuite
System.out.println("Before Suite");
}
@BeforeTest
System.out.println("Before Test");
@BeforeClass
System.out.println("Before Class");
@BeforeMethod
System.out.println("Before Method");
@Test
System.out.println("Test 1");
@Test
System.out.println("Test 2");
}
@AfterMethod
System.out.println("After Method");
@AfterClass
System.out.println("After Class");
@AfterTest
System.out.println("After Test");
@AfterSuite
System.out.println("After Suite");
Precondition Annotations: These annotations are executed before the test. It is made up of the following
annotations:
@BeforeMethod
@BeforeClass
@BeforeSuite
@BeforeTest
Test Annotations: These annotations are defined just before the test methods. It also includes the
following annotations:
@Test
Postcondition Annotations: These annotations are executed after the test methods. It also includes the
annotations listed below:
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
Meta-Annotations: These annotations are used in TestNG to create custom annotations. They provide
additional test metadata, such as how the test should be grouped, what data should be used for the
test, and which groups should be excluded from the test.
@TestInstance
@Parameters
@DataProvider
@Listeners
@Factory
@Test
In TestNG, the @Factory annotation is used to create test instances at runtime. It enables you to
generate test classes or instances dynamically based on runtime conditions or parameters.
You can use the @Factory annotation to create multiple instances of the same test class with different
data sets or parameters and run them in parallel to improve test execution speed. Here is an example of
@factory annotations
@Factory
return result;
The @Factory annotation is used to create multiple instances of the same test class, each with a
different set of input parameters or configurations. This is useful when running the same test with
different data sets or configurations or when running tests in parallel to save time during testing.
Meanwhile, @DataProvider annotation supply test data to a test method. It allows you to separate the
test data from the test logic, making your test code easier to maintain and reuse. @DataProvider can be
used to provide test data from a variety of sources, including arrays, Excel sheets, databases, and
external files.
In TestNG, the @Listener annotation is used to define listeners, which are classes that listen to events
that occur during the execution of a TestNG test. Listeners can be used to customize or enhance
TestNG's behavior by adding extra functionality such as logging, reporting, or customizing the test
execution flow.
You can specify one or more listener classes to be invoked during test execution by using the @Listener
annotation. This enables you to extend and customize TestNG's behavior to meet your specific testing
requirements.
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@TestMethod
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
26. What are the attributes supported by @Test annotation in TestNG?
The following is an exhaustive list of the attributes supported by the @Test annotation in TestNG:
alwaysRun
dataProvider
dataProviderClass
description
enabled
expectedExceptions
expectedExceptionsMessageRegExp
groups
invocationCount
invocationTimeOut
priority
successPercentage
testName
timeOut
dependsOnGroups
dependsOnMethods
skipFailedInvocations
alwaysResolveDependencies
The alwaysRun attribute ensures that a test method is always executed, regardless of whether a
dependent method fails or is skipped.
28. Which attribute is used to provide data to test method in Data-driven testing?
In Data-driven testing, we use the dataProvider attribute of the @Test annotation in TestNG to provide
data to a test method.
The dependsOnMethods attribute in TestNG is used to specify a test method's dependency on one or
more other test methods. This property allows us to ensure that certain test methods are run in the
correct order.
When one test method is dependent on another, TestNG will not run the dependent method until all of
its dependencies have passed successfully. The dependent method will be skipped if any of the
dependencies fail or are skipped.
The dependsOnGroups attribute in TestNG is used to specify a test method's dependency on one or
more groups of test methods. This property allows us to ensure that certain groups of test methods are
executed in the correct order.
When a test method is dependent on a group of test methods, TestNG will not execute the dependent
method until all of the test methods in the specified group have successfully passed. If any of the group's
test methods fail or are skipped, the dependent method will also be skipped.
The @BeforeTest annotation is used to run the setup code before running all of the test methods in the
<test> tag of a TestNG XML file. The @BeforeMethod annotation, on the other hand, is used to run the
setup code before each individual test method in a class.
32. How will you make test cases dependent on each other?
Using the @Test annotation's dependsOnMethods attribute, we can make test cases dependent on one
another in TestNG. This attribute allows us to specify which test methods must be run before a specific
test method can be executed.
After all of the test methods have been completed, TestNG generates several reports by default. Such
as:
Emailable reports
Apart from these, the TestNG Listener API allows you to create custom reports. Custom listeners can be
created by developers to generate reports in a variety of formats, including JSON, PDF, and CSV.
34. What are the different ways to produce reports for TestNG results?
TestNG provides several methods for producing test result reports. Here are some common methods
for generating reports for TestNG results:
TestNG Default Reports: For test results, TestNG provides default HTML reports. These reports include
detailed information about the tests, such as test methods, groups, execution time, and test status.
TestNG Ant Task: TestNG includes an Ant task for creating customized HTML reports. You can use this
task to create customized reports with logos, headers, and footers.
ExtentReports: ExtentReports is a popular reporting library that generates rich, interactive HTML reports
for TestNG results. It has features such as pie charts, line charts, and screenshots.
Allure Reports: Another popular reporting library that provides detailed and interactive HTML reports
for TestNG results is Allure Reports. It includes features such as history, tags, and attachments.
ReportNG: ReportNG is a TestNG custom reporting plugin that generates detailed HTML reports with
customizable templates. It includes features such as screenshots, pie charts, and test logs.
The emailable report is generated by default in the TestNG project's output directory, in the folder
named "test-output." The emailable report's filename is "emailable-report.html."
So, for a TestNG project, the full path to the emailable report would look something like this:
<project-dir>/test-output/emailable-report.html
The index.html report is one of TestNG's default reports, providing an overview of the test results as
well as links to other reports such as the emailable report, testng-results.xml, and testng-failed.xml.
The index.html report is generated by default in the TestNG project's output directory under the folder
named "test-output." The index.html report's filename is "index.html."
<project-dir>/test-output/index.html
It should be noted that the output directory can be specified in the TestNG XML file by using the
"outputDirectory" attribute of the "suite" element.
37. How to use TestNG Reporter Class for the log generation?
The TestNG Reporter class is a built-in class for logging messages during test execution. Follow these
steps to use the Reporter class for log generation:
import org.testng.Reporter;
Reporter.log("Log message");
As a second argument to the log() method, you can optionally include a log level, such as "debug",
"info", "warning", or "error":
To view the Reporter class's logs, enable the verbose output option in the TestNG XML file:
In TestNG, you must use a combination of listeners, reporters, and frameworks to generate a
customized report. You can take the following steps:
You can distribute the project report generated by TestNG in the following ways:
HTML Reports: TestNG generates HTML reports with a detailed summary of test execution results. You
can distribute these reports to others by simply sending the HTML file or hosting the file on a server and
sending the link.
Email Reports: TestNG also allows you to generate and send an email report with a summary of the test
execution results. In the testng.xml file, you can configure the email settings, including the email
recipients, subject, and body.
CI/CD tools: Integration with Continuous Integration/Continuous Deployment (CI/CD) tools: If you use a
CI/CD tool like Jenkins or Bamboo, you can integrate TestNG with these tools to automatically generate
and share test execution reports.
TestNG groups enable you to categorize your tests and control their execution based on these
categories. By grouping your tests, you can easily select which to run and which to skip based on the
group to which they belong.
You can organize your tests however you see fit, such as by functionality, priority, or environment.
Run a subset of the tests in your test suite rather than all of them, which can save you time and effort.
Test execution in different groups concurrently, which allows for faster execution and better test
coverage.
managing and organizing your tests according to groups, making it easier to maintain and update your
test suite.
Groups are a collection of multiple test case methods that have been combined into a single unit. We
can operate directly on the group by grouping, which will reflect on all of the test case methods under it.
Furthermore, in TestNG, we can define a group of groups as a larger unit of test methods.
43. How do you exclude a group from the test execution cycle?
The exclusion a group in TestNG indicates that this group will not run throughout the execution and will
be ignored by TestNG. Furthermore, the name of the group to be excluded is defined in the XML file
using the following syntax:
<groups>
<run>
</exclude>
</run>
</groups>
You can make a group of groups in TestNG by including one or more groups as dependencies on another
group. The following are the steps for creating a group of groups in TestNG:
In your test class, use the @Test annotation with the groups attribute to define groups. As an example:
@Test(groups = {"group1"})
// test code
@Test(groups = {"group2"})
// test code
}
@Test(groups = {"group3"})
// test code
Make a new group with the groups you want to group together as dependencies. As an example:
// test code
In the preceding example, the testGroupOfGroups method is a member of the groupOfGroups group
and is dependent on the groups group1, group2, and group3.
Use TestNG to run your tests. The testGroupOfGroups method will only be called if all of the tests in
groups 1, 2, and 3 passes.
You can design complicated test hierarchies by using group dependencies, which allow you to run tests
in a certain order and ensure that all dependent tests pass before running a given test.
45. How to group multiple test methods in a single group using TestNG?
With the @Test annotation's groups feature, you can organize many test methods into a single group in
TestNG. Here's how to use TestNG to group many test methods into a single group:
Syntex:
@Test(groups = {"GroupName"})
With the @Test annotation's groups feature, you can group multiple test methods into multiple groups
in TestNG.
To divide a test method into numerous groups, use the groups attribute to give a comma-separated list
of group names. As an example:
// test code
}
The college method is included in both Science and Maths in the preceding example. Similarly, you can
organize numerous test methods into several groups by using the groups attribute to define the same
group names for each method.
The priority attribute of the @Test annotation in TestNG allows you to group multiple test methods with
different priorities. The priority attribute specifies the order in which TestNG should execute the test
methods.
To divide a test method into numerous groups, use the groups attribute to give a comma-separated list
of group names. As an example:
// test code
// test code
// test code
// test code
}
There are two groups in this example, Science and Maths, as well as four test methods, testMethod1(),
testMethod2(), testMethod3(), and testMethod4(). The priority attribute specifies the order in which the
test methods within their respective groups should be executed.
An inclusion group is a group that is included in test execution. The exclusion group is a group that is
excluded from test execution.
TestNG allows us to make a single test rely on a group of tests. We use the dependsOnGroups attribute
in the TestNG test case file to execute in this manner. The name of the group on which we want this
method to rely is the value of this attribute. An illustration of this is provided below:
import org.testng.annotations.Test;
@Test(groups = {"login"})
Asserting in TestNG is a code element that assists us in determining whether the expected and actual
results are equal. To determine whether the test case passed or failed, we use the built-in "Assert" class
and many of its methods in TestNG. Furthermore, in TestNG, a test case is considered a "pass" if none of
the assert methods throw an exception during execution. The syntax for TestNG assert is as follows:
import org.testng.Assert;
// perform assertion
assertEquals(expectedValue, actualValue, message): It compares two values and determines if they are
equal.
assertTrue(condition, message): This assertion helps whether or not the specified condition is true.
assertFalse(condition, message): This assertion defines if the specified condition is true or false.
assertNull(object, message): This assertion determines whether or not the specified object is null.
Soft Asserts
Firm Assertion
53. Define soft assert in TestNG and describe how they are different from hard assert
Soft asserts in TestNG mean that the tests will continue to run even if the assertion throws an exception
in the middle of the execution. Furthermore, TestNG does not include Soft asserts by default, so an
additional org.testng.asserts.Softassert package import is required.
Soft assertions differ from hard assertions in that when a hard assertion fails, the test terminates
immediately, and the remaining test steps are skipped. When a soft assertion fails, however, the test
continues to run, and any subsequent assertions are also run. Only when the test is completed are the
test results, including soft assertion failures, reported, but the test is not terminated.
Dependencies are used in TestNG to specify the order in which test methods should be executed. A
dependency is a relationship between two or more test methods that specifies that one or more tests
must be run before another.
@Test(dependsOnMethods = {"testMethod1"})
@Test
In TestNG, we can create dependent tests by specifying the dependonMethods parameter on the @Test
annotation. The attribute's value is the name of the method on which we want this method to rely. This
method is applied as follows:
@Test
@Test(dependsOnMethods = {"loginTest"})
public void dashboardTest() {
Through the TestNG XML file, we can also create dependencies between groups. Such dependencies
denote a group's reliance on another. Here's an example of how to use the testng.xml file to create a
dependency between two test methods:
<test name="MyTest">
<classes>
<class name="com.example.MyTestClass">
<methods>
</methods>
</class>
</classes>
</test>
dependsOnMethods
dependsOnGroups
58. How many types of dependencies can you achieve by using TestNG?
TestNG is a Java testing framework that allows for various types of dependencies between test methods.
The following dependencies can be achieved by using TestNG:
Dependencies Attribute
Priorities are used in TestNG to define the order in which test methods should be executed. in the
@Test annotation, it is used to assign priorities to test methods. Test methods with lower priority values
will be executed first, followed by methods with higher priority values.
In our dedicated blog, you can learn practical examples of how to setpriorities in TestNG.
Priorities for test methods in TestNG can be set using the priority attribute in the @Test annotation.
Here's an example:
@Test(priority=1)
// test code
@Test(priority=2)
// test code
@Test(priority=3)
// test code
}
In this example, testMethod1() is the most important and will be executed first, followed by
testMethod2() and, finally, testMethod3(). You can set the execution order of your test methods by
assigning any integer value to the priority attribute.
Parameterization in TestNG, refers to the process of passing parameters to a test method so that it can
be run multiple times with different data sets. This feature is especially helpful when running the same
test with different input values or test scenarios.
The "@DataProvider" annotation in TestNG can be used to parameterize code. The DataProvider
annotation specifies a method that provides data to a test method. The data provider method returns a
two-dimensional array of objects, with each row representing a set of data used to run the test method.
Optional parameters behave similarly to the default case in TestNG parameterization. When no other
parameters are defined for that test case method, we use the optional parameter.
The @Optional annotation also declares the optional parameter. We don't define
the @Optional parameter above the test method definition but rather alongside it.
Following that, the following code snippet shows how to declare optional parameters in TestNG:
@Test
The "@Optional" annotation is used in this example to specify a default value for the "optionalParam"
parameter. If this parameter is not supplied when the test method is run, its value will be "default."
The timeout attribute in TestNG is used to specify the maximum amount of time (in milliseconds) that a
test method should be allowed to run before being forcefully terminated. This property is useful when a
test method becomes stuck in an infinite loop or takes too long to complete, causing the entire test
suite to stall. It can be declared at
Syntex:
@Test(timeout = 5000)
Parallel test execution in TestNG means running multiple test cases or test suites on multiple threads at
the same time. TestNG is designed to support the parallel execution of tests, which allows testers to run
multiple tests concurrently, reducing overall test execution time.
Tests: This value will be used to run all test cases contained within the <test>tag.
Classes: All of the test cases contained within the XML classes will run in parallel.
Instances: This value will run all test cases concurrently within the same instance.
Example:
@Test(expectedExceptions = ArithmeticException.class)
int a = 5;
int b = 0;
int c = a / b;
}
68. Can we disable a test in TestNG? If so, explain how?
Yes, you can disable a test in TestNG by annotating the test method with @Test(enabled=false). Once
you disable the test, it won't execute when you run the test script again.
@Test(enabled=true)
During test execution, the Reporter class in TestNG is used to generate additional logs or custom output.
It allows developers or testers to log additional information or messages during test execution, which
can help with debugging or troubleshooting test failures.
70. Define the syntax for generating logs through the reporter class in TestNG
The Reporter.log() method in TestNG can be used to generate logs via the Reporter class. This method's
syntax is as follows:
Listeners are classes in TestNG that can be used to customize and extend TestNG's behavior during test
execution. They enable custom actions to be performed before or after specific events, such as the start
or end of a test case or suite, the success or failure of a test, or the generation of a test report.
TestNG comes with a set of built-in listeners that you can use right away, or you can create your own
custom listeners by implementing the necessary interfaces.
In the TestNG XML configuration file, add the <listeners> tag inside the <suite> tag to declare listeners.
Here's an illustration:
<listeners>
<listener class-name="com.example.MyTestListener"/>
</listeners>
<class name="com.example.MyTestClass"/>
</classes>
</test>
</suite>
Listeners can also be declared by annotating your test class with the @Listeners annotation. Here's an
example:
import org.testng.annotations.Listeners;
@Listeners(com.example.MyTestListener.class)
// test methods...
TestNG includes a number of built-in listeners that you can use to customize and extend your test suite's
behavior. Here's a quick rundown of the most common listeners in TestNG:
IInvokedMethodListener
IMethodInterceptor
IAnnotationTransformer
IAnnotationTransformer2
IReporter
ISuiteListener
IHookable
ITestListener
To implement the IAnnotationTransformer interface in TestNG, you need to create a new Java class that
implements the IAnnotationTransformer interface, implement the transform() method to modify
the ITestAnnotation object associated with the test method, and add the listener to your test suite by
including it in your TestNG XML configuration file or annotating your test class with
the @Listeners annotation.
The default priority for a test method in TestNG is 0. This means that if a test method is not explicitly
assigned a priority using the @Test annotation, it will be assigned a priority of 0 by default.
Sure, here are the step-by-step instructions for implementing TestNG ITestListener:
In each of these methods, add the custom actions you want to perform, such as logging, reporting, or
modifying test results.
Include the tag and specify the full class name of your listener in your TestNG XML configuration file to
add the listener class.
Alternatively, you can use the @Listeners annotation on your test class and specify the full class name of
your listener.
When you run your test suite, the listener methods will be executed in response to the test events,
allowing you to take custom actions.
An exception test in TestNG is a type of test that determines whether or not a method throws a specific
exception. When an exception is thrown, it is used to ensure that a method behaves as expected.
To create an exception test in TestNG, use the @Test annotation's expectedExceptions attribute. This
attribute specifies the type of exception that the method is expected to throw.
Click the Install button after selecting the TestNG for Eclipse plugin from the search results.
The SkipException class in TestNG is a built-in exception class that can be used to skip a test method
during execution. The message passed to the SkipException class's constructor is displayed in the test
results, indicating why the test was skipped.
81. What is the time unit we specify in test suites and test cases?
The time unit specified in TestNG test suites and test cases in seconds.
</suite>
In this example, we have set the test suite timeout to 180 seconds.
With the help of the command line, where you specify the TestNG JAR file and the test suite XML file
with the java command.
Invoke with the integrated development environment (IDE) such as Eclipse, IntelliJ IDEA, or NetBeans.
You can also use build tools such as Maven, and Gradle
Use a continuous integration (CI) server such as Jenkins, Travis CI, or CircleCI to run TestNG tests.
Using a test runner such as the TestNG Eclipse plugin, TestNG Maven plugin, or TestNG Ant task to run
TestNG tests.
You can use TestNG to build a data-driven framework by following these steps:
Make a TestNG XML file with the test parameters and data provider. A data provider is a method that
provides test data to other methods.
Implement the data provider method to get test data from a data source like a CSV file, Excel sheet, or
database.
Add the data provider attribute to the @Test annotation of the test method to indicate that the data
provided by the data provider method will be used by the test method.
Use the test data to execute the test logic in the test method.
@Test(dataProvider = "testData")
System.out.println("Name: " + firstName + " " + lastName + ", Age: " + age);
84. How to exclude a particular test method from a test case execution?
You can use the enabled attribute of the @Test annotation to exclude a specific test method from a
TestNG test case execution. The enabled attribute specifies whether or not a test method should be
executed. If the enabled attribute is set to false, the test method will be skipped during the execution of
the test case.
@Test(enabled = false)
// Test logic
The org.testng.SkipException class can be used to prevent a @Test method from being executed in
TestNG. This class is used to throw a skip exception, which instructs TestNG to skip the test method
execution.
import org.testng.SkipException;
import org.testng.annotations.Test;
C:UsersAdminDesktopLTlearninghubworkspaceTestNGtestingtutoriol
set
classpath=C:UsersAdminDesktopLTlearninghubworkspaceTestNGtestingtutoriolin;C:UsersAdminDesktop
LTlearninghubworkspaceTestNGtestingtutoriollib*
In TestNG, the @Test(threadPoolSize=x) annotation is used to specify the number of threads to use
when running a test method in parallel. The x parameter is an integer value that indicates the thread
pool size.
When you use this annotation, TestNG will create a pool of threads and distribute test method instances
among them. Each thread will independently and concurrently execute its assigned test method
instance with the other threads.
In TestNG, the @Test(invocationCount=x) annotation is used to specify how many times a test method
should be invoked during the test execution. The x parameter is an integer value that specifies how
many times the test method should be run.
When this annotation is used, TestNG will run the test method as many times as specified, each time
with a new test instance. This is useful in testing scenarios where the test method must be run multiple
times with different input data or conditions.
When the thread-count attribute is set to a value greater than one, TestNG will create multiple threads
and distribute the test methods among them for parallel execution.
The verbose attribute in TestNG is used to limit the amount of information displayed in the console
output during test execution.
The verbose attribute accepts integer values ranging from 0 to 10, with 0 being the least verbose and 10
being the most verbose. The default value is 1, which displays basic test execution information.
91. How many ways by which can we pass parameter values to test methods?
We can pass parameter values to test methods in the following ways in TestNG:
We can use the RestAssured library and write test methods that send HTTP requests and validate the
responses to use TestNG to test RESTful web services. To test various scenarios, we can also use TestNG
data providers and parameterization.
Appium, an open-source tool for automating mobile app testing, can be used to test TestNG mobile
applications. To define the desired capabilities of the mobile device, we can create a TestNG test class
and write test methods that interact with the mobile app by finding elements and performing actions on
them. TestNG annotations can be used to manage the test environment and control the test execution
order.
Install the required software and configure the system variables to create the Appium environment.
Create a new TestNG test class and specify the capabilities of the mobile device to be tested.
Create test methods that interact with the mobile app by locating and acting on elements.
Control the test execution order and manage the test environment with TestNG annotations
@DataProvider(name = "testData")
{"Mehul", "password1"},
{"Gadhiya", "password2"},
{"Devya", "password3"}
};
Add the @DataProvider annotation to the method and give the data provides a name.
Add the dataProvider attribute to the ,@Test annotation in the test method and set it to the name of
the data provider.
@Test(dataProvider = "testData")
To receive test data, add parameters to the test method. In the preceding example, we have two
parameters, username, and password, which will be set to the data provider's values.
To perform the test and assert the results, use the test data in the test method.
TestNG is a testing framework inspired by JUnit, but it offers additional features like parallel test
execution, flexible test grouping, and better reporting.
@Test
@BeforeTest is used to run setup code before any test method in the test class, and @AfterTest is used
to run cleanup code after all test methods in the class.
Use the @DataProvider annotation to supply data to a test method, like this:
java
@DataProvider(name = "myData")
@Test(dataProvider = "myData")
Use the parallel attribute in the <suite> tag of your testng.xml file or annotate your test class with
@Listeners({ParallelListener.class}) to enable parallel execution.
It specifies that a test method depends on the successful execution of one or more other test methods
before it can run.
Use the priority attribute in the @Test annotation to specify the execution order, where lower values
execute first.
@Parameters is used to specify parameters for a test method, and you can define these parameters in
your testng.xml file.
How do you perform group testing in TestNG?
Use the groups attribute in the @Test annotation to assign a test method to one or more groups, then
include or exclude groups in your testng.xml file.
You can use the preserveOrder attribute in the <suite> tag of your testng.xml file to specify that test
methods should run in their declared order.
@Listeners is used to add custom listeners to your test class, which can perform actions before or after
test methods.
Soft Assert allows you to continue executing test steps even after an assertion fails. Here's an example:
java
softAssert.assertEquals(actual, expected);
TestNG listeners are interfaces that allow you to customize test execution. Here's an example of a
custom listener:
java
}
How can you skip a test method in TestNG?
Use the @Test(enabled = false) annotation or the @Test annotation with enabled = true or false to skip
or execute a test method.
@DataProvider supplies data to test methods, while @Factory creates instances of test classes, allowing
dynamic test creation.
TestNG provides built-in HTML reports. You can also integrate it with tools like ExtentReports or
TestNG's IReporter interface for custom reporting.
Add the TestNG dependency in your pom.xml, and then configure your test classes and suites in a
testng.xml file.
@BeforeSuite runs setup code before all test methods in a suite, and @AfterSuite runs cleanup code
after all test methods.
Explain how to pass parameters to a TestNG test using the testng.xml file.
Define parameters in the <parameter> tag inside <test> or <suite> tags in testng.xml, and reference
them using @Parameters in your test class.
How can you run TestNG tests from the command line?
Use the java -cp command with the org.testng.TestNG class and specify the testng.xml file as an
argument.
Explain testNG annotation in sequence with real time scenario?example of @After@Before in TestNG?
selenium interview qus/testng
How you can specify your group dependencies in the testng.xml file. You use the <dependencies> tag to
achieve this
@Parameters({ "first-name" })
@Test
public void testSingleString(String firstName) {
System.out.println("Invoked testString " + firstName);
assert "Cedric".equals(firstName);
}
Question: Explain how you can achieve parallel test execution in TestNG, and what are the key attributes
for parallel configuration?
Answer: Parallel execution in TestNG can be achieved using the parallel attribute at the suite, test, or
method level. Key attributes include methods, tests, instances, and classes.
Question: How can you implement data-driven testing in TestNG, and what annotations or attributes are
involved?
Answer: Data-driven testing is achieved using the @DataProvider annotation and associating it with the
dataProvider attribute in the @Test annotation.
Question: Describe how you handle test dependencies in TestNG, and what annotations are used for this
purpose.
Answer: TestNG allows dependency management using the dependsOnMethods and dependsOnGroups
attributes within the @Test annotation.
Question: How do you group tests in TestNG, and what mechanisms are available to control the
execution of specific groups?
Answer: Tests can be grouped using the @Test(groups = "group_name") annotation. Execution control
involves including or excluding specific groups in the XML suite file.
Question: Explain the role of listeners in TestNG, and how you can generate detailed test reports using
listeners.
Answer: Listeners like IInvokedMethodListener and ITestListener allow you to customize test behavior
and generate detailed reports. Utilize tools like Extent Reports for enhanced reporting.
Question: How can you parameterize your tests in TestNG, and what is the significance of the
@Parameters annotation?
Answer: Test parameterization is achieved using the @Parameters annotation in conjunction with the
parameter attribute in the @Test annotation.
Question: What is a TestNG suite, and how can you configure and run multiple test classes using XML
configuration?
Answer: A TestNG suite is a collection of test classes. Configuration is done using the XML suite file
where you define test classes, groups, and parameters.
Question: How can you handle expected exceptions in TestNG, and what annotations are involved?
Question: Explain the concept of soft assertions in TestNG and how they differ from traditional
assertions.
Answer: Soft assertions, provided by the SoftAssert class, allow the execution of subsequent test steps
even if an assertion fails, providing a comprehensive test report.
Question: Discuss how you integrate TestNG with Selenium for automated testing, and what are the
benefits of this integration.
Answer: TestNG and Selenium integration involves creating test scripts using TestNG annotations,
allowing better test organization, parallel execution, and reporting.