Automation QA Testing Course Content

TestNG Interview Questions

 TestNG Interview Questions:

1)Can we set the priority of a test case to zero with @Test annotation?

Ans)Yes

2. Annotations in testing ?

Annotations in testing are special labels or meta-data added to the test code to control how tests are executed and to provide additional information about the tests. Some common annotations used in testing are:

  1. @Test: This annotation is used to mark a method as a test method. When TestNG runs, it will identify and execute all methods marked with this annotation.

  2. @BeforeTest: This annotation is used to mark a method that should be executed before any test method belonging to the classes inside the <test> tag is run.

  3. @BeforeMethod: This annotation is used to mark a method that should be executed before each test method.

  4. @AfterTest: This annotation is used to mark a method that should be executed after all the test methods belonging to the classes inside the <test> tag have run.

  5. @AfterMethod: This annotation is used to mark a method that should be executed after each test method.

  6. @DataProvider: This annotation is used to mark a method that provides data for a test method. The data returned by this method can be used by one or multiple test methods.

  7. @Factory: This annotation is used to mark a method that returns an array of test classes. TestNG will create an instance of each class in the array and run the test methods.

  8. @Listeners: This annotation is used to specify listeners for a test. Listeners can be used to monitor the test execution and perform additional processing, such as logging or reporting.

  9. @Parameters: This annotation is used to pass parameters to a test method.

  10. @Test(dependsOnMethods={"methodName"}): This annotation is used to specify that a test method depends on another test method. If the specified method fails, the test method annotated with dependsOnMethods will not be executed

@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

3. Difference between @BeforeTest and @BeforeMethod ?

The @BeforeTest and @BeforeMethod annotations in TestNG are used to define methods that are executed before a test run and before each test method respectively.

@BeforeTest: This method is executed once before any test method belonging to the classes inside the <test> tag is run. This method can be used for one-time setup, such as initializing objects or setting up a database connection, that will be used in the test methods.

@BeforeMethod: This method is executed before each test method. This method can be used for test method-specific setup, such as creating test data or setting up test conditions.

Here's an example to illustrate the difference between the two:

public class TestClass { private Connection connection; @BeforeTest public void setupDB() { connection = getDBConnection(); } @BeforeMethod public void insertTestData() { insertData(connection, "testdata1"); } @Test public void testMethod1() { // test method implementation } @Test public void testMethod2() { // test method implementation } }

In this example, the setupDB() method is executed once before any test method, while the insertTestData() method is executed before each test method

4. Soft assert vs Hard Assert ?

n TestNG, a "hard assert" immediately stops the execution of a test if the assert statement fails. If a hard assert statement fails, the test is marked as failed and no further statements in the test method are executed.

On the other hand, a "soft assert" allows the execution of a test to continue even if an assert statement fails. The test is only marked as failed if a soft assert statement fails and the test is still executing. At the end of the test, you can retrieve the information about all the failed assertions and perform additional processing, such as logging or reporting.

Here is an example of how to use soft assert in TestNG:

public class TestClass { @Test public void testMethod() { SoftAssert softAssert = new SoftAssert(); softAssert.assertEquals(1, 2, "First assertion failed"); System.out.println("Second assertion"); softAssert.assertEquals(2, 2, "Second assertion failed"); softAssert.assertAll(); } }

In this example, the "assertEquals" method of the "SoftAssert" class is used instead of the "assertEquals" method of the "Assert" class. The "softAssert.assertAll()" method must be called at the end of the test method to indicate that all the assertions have been executed and to trigger the assertion failures.

5. How to pass parameters to test methods 

There are several ways to pass parameters to test methods in TestNG:

  1. Through testng.xml file: You can pass parameters to test methods by specifying them in the testng.xml file and using the "@Parameters" annotation in the test method. For example:
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite Name"> <test name="Test Name"> <parameter name="param1" value="value1"/> <parameter name="param2" value="value2"/> <classes> <class name="test.TestClass"/> </classes> </test> </suite> public class TestClass { @Test @Parameters({"param1", "param2"}) public void testMethod(String param1, String param2) { System.out.println("Param1: " + param1); System.out.println("Param2: " + param2); } }
  1. Through Data Providers: You can pass parameters to test methods by returning an array of objects from a Data Provider and using the "@DataProvider" annotation in the test method. For example:
@DataProvider(name="testData")
public Object[][] createData() {
   return new Object[][] {
      { "Cedric", new Integer(36), "Paris" },
      { "Anne", new Integer(37), "London" },
   };
}

@Test(dataProvider = "testData")
public void testMethod(String name, Integer age, String city) {
   System.out.println("Name: " + name + "; Age: " + age + "; City: " + city);
}

@DataProvider(name="testData") public Object[][] createData() { return new Object[][] { { "Cedric", new Integer(36), "Paris" }, { "Anne", new Integer(37), "London" }, }; } @Test(dataProvider = "testData") public void testMethod(String name, Integer age, String city) { System.out.println("Name: " + name + "; Age: " + age + "; City: " + city); }

In this example, the "createData" method is annotated with "@DataProvider" and returns an array of objects. The "testMethod" method is annotated with "@Test" and specifies the "dataProvider" attribute as "testData", which is the name of the Data Provider. When the test is run, the "testMethod" method will be run twice, once for each row of data in the array returned by the "createData" method.

  1. Through TestNG Configuration methods: You can pass parameters to test methods by using the "@BeforeTest" or "@BeforeMethod" method and making them global to the class. For example:
public class TestClass { private String param1; private String param2; @BeforeTest public void beforeTest() { param1 = "value1"; param2 = "value2"; } @Test public void testMethod() { System.out.println("Param1: " + param1); System.out.println("Param2: " + param2); } }

6. Use of data provider ?

A Data Provider in TestNG is a method that provides data to a test method. It returns an array of objects, which are passed as arguments to the test method. Data Providers are used to run a test method multiple times with different sets of data.

To use a Data Provider, you need to annotate a method with the "@DataProvider" annotation and specify the name of the Data Provider. Then, you can use the name of the Data Provider in the "@Test" annotation of the test method to specify that this method should be run with the data from the Data Provider.

The signature of a Data Provider method must be public Object[][] methodName(). The return value must be a two-dimensional array of objects. Each row of the array represents a set of data that will be passed to the test method.

Here is an example:

@DataProvider(name="testData") public Object[][] createData() { return new Object[][] { { "Cedric", new Integer(36) }, { "Anne", new Integer(37)}, }; } @Test(dataProvider = "testData") public void testMethod(String name, Integer age) { System.out.println("Name: " + name + "; Age: " + age); }

In this example, the "createData" method is annotated with "@DataProvider" and returns an array of objects. The "testMethod" method is annotated with "@Test" and specifies the "dataProvider" attribute as "testData", which is the name of the Data Provider. When the test is run, the "testMethod" method will be run twice, once for each row of data in the array returned by the "createData" method.

7. Use of invocationCount, enabled, priority, dependsOnMethod, dependsOnGroups, alwaysRun, dataProvider, groups, timeout, expectedExceptions, singleThreaded, etc 

8. testNg xml structure ?

The structure of a testng.xml file in TestNG is as follows:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite Name">

  <test name="Test Name">

    <groups>

      <run>

        <!-- include or exclude groups here -->

      </run>

    </groups>

    <classes>

      <class name="Class Name"/>

      <!-- additional class elements here -->

    </classes>

  </test>

  <!-- additional test elements here -->

  <listeners>

    <!-- listeners here -->

  </listeners>

</suite>

In this example:

  • The "suite" element is the root element of the testng.xml file and defines the TestNG test suite. The "name" attribute specifies the name of the test suite.
  • The "test" element defines a test case and is a child of the "suite" element. The "name" attribute specifies the name of the test case.
  • The "groups" element specifies the groups that should be included or excluded in the test run. The "include" and "exclude" elements are used to include and exclude groups, respectively.
  • The "classes" element specifies the classes that should be included in the test run. Each "class" element specifies a class name.
  • The "listeners" element specifies listeners that should be used in the test run. Listeners are used to listen to test events and perform actions based on those events.

You can also specify test methods and include and exclude methods, set the priority of tests, set test parameters, and configure many other settings using the testng.xml file.

9. How to group testcases ?

In TestNG, you can group test cases using the "groups" attribute in the @Test annotation. The "groups" attribute takes a comma-separated list of group names, and you can assign one or more groups to each test method. You can then run only the tests belonging to a specific group, or exclude tests belonging to a specific group, by specifying the group names in the testng.xml file.

Here is an example of how to group test cases in TestNG:

import org.testng.annotations.Test; public class TestClass { @Test(groups = { "functional", "smoke" }) public void testMethod1() { // Test code } @Test(groups = { "functional" }) public void testMethod2() { // Test code } @Test(groups = { "smoke" }) public void testMethod3() { // Test code } }

In this example, testMethod1 belongs to both the "functional" and "smoke" groups, testMethod2 belongs to the "functional" group, and testMethod3 belongs to the "smoke" group.

To run only the tests belonging to a specific group, you can use the "groups" attribute in the <test> tag in the testng.xml file, like this:

<suite name="My Suite"> <test name="My Test"> <groups> <run> <include name="functional"/> </run> </groups> <classes> <class name="com.example.TestClass"/> </classes> </test> </suite>

In this example, only the tests belonging to the "functional" group will be run. The tests belonging to the "smoke" group will be excluded.

You can also exclude tests belonging to a specific group by using the "exclude" attribute instead of the "include" attribute, like this:

<suite name="My Suite"> <test name="My Test"> <groups> <run> <exclude name="smoke"/> </run> </groups> <classes> <class name="com.example.TestClass"/> </classes> </test> </suite>

In this example, all tests except those belonging to the "smoke" group will be run. The tests belonging to the "smoke" group will be excluded.

10. Use of IRetryAnalyzer class "

The IRetryAnalyzer class in TestNG is an interface used to specify a custom retry logic for failed test cases. If a test method is annotated with the @Test annotation and fails, the IRetryAnalyzer's "retry" method will be called. If the retry method returns "true," TestNG will rerun the test case again, and the process will repeat until either the test case passes or the retry method returns "false."

By implementing this interface, you can add a custom retry logic to handle test cases that are flaky (i.e. they sometimes pass and sometimes fail) and ensure that your tests run reliably. The IRetryAnalyzer class is a useful tool for improving the reliability of your test suite.

11. How to run failed testcases 

There are several ways to rerun failed test cases in TestNG:

  1. TestNG XML: You can create a TestNG XML file that includes only the failed test cases, and then run the XML file to rerun only the failed tests.

  2. TestNG listeners: You can use the IRetryAnalyzer interface to implement a custom retry logic for failed test cases, and then register the retry logic as a TestNG listener.

  3. TestNG suites: You can create a TestNG suite that includes only the failed test cases, and then run the suite to rerun only the failed tests.

  4. TestNG reporters: You can use TestNG reporters to generate reports for failed test cases, and then rerun only the failed tests.

You can choose the method that best fits your needs, depending on the specific requirements of your project.

12. How to perform parallel testing. 

TestNG supports parallel testing, which allows you to run multiple test cases concurrently, in parallel. There are two ways to perform parallel testing in TestNG:

  1. Parallel by methods: You can run multiple test methods concurrently by specifying the "parallel" attribute in the @Test annotation.

  2. Parallel by classes: You can run multiple test classes concurrently by specifying the "parallel" attribute in the <test> tag in the TestNG XML file.

13. What level user can perform parallel testing 

Parallel testing can be performed by any level of user who has basic knowledge of TestNG framework and testing concepts. Parallel testing requires the ability to write tests in TestNG and understand the concepts of test parallelism, such as threads, invocation counts, and timeouts.

The level of expertise needed to perform parallel testing depends on the complexity of the tests being run in parallel and the specific requirements of the project. For simple projects with a small number of tests, a beginner or intermediate user may be able to perform parallel testing. For complex projects with a large number of tests, an advanced or expert user may be needed.

14. Use of ISuiteListener Methods 

ISuiteListener is a TestNG interface that provides methods that are called before and after a TestNG suite runs. By implementing the ISuiteListener interface, you can customize TestNG's behavior before and after a suite of tests runs. The following are the methods of ISuiteListener interface:

  1. onStart: This method is called before the start of the suite run. It is useful for setting up any pre-suite test environment.

  2. onFinish: This method is called after the suite run is completed. It is useful for cleaning up any resources that were created during the suite run.

By using ISuiteListener, you can add custom behavior to your test suite, such as setting up a test environment, logging test results, or cleaning up resources. To use ISuiteListener, you must implement the ISuiteListener interface and register it as a TestNG listener. Here is an example of how to implement and use ISuiteListener in TestNG:

public class SuiteListener implements ISuiteListener { @Override public void onStart(ISuite suite) { // Custom code to run before the start of the suite } @Override public void onFinish(ISuite suite) { // Custom code to run after the completion of the suite } }

In your testng.xml file, you can register the listener by adding the following code:
<listeners> <listener class-name="com.example.SuiteListener"/> </listeners>

15. Use of TestListenerAdaptor methods ?

TestListenerAdapter is a class in TestNG that implements ITestListener, an interface that provides methods that are called before and after a test run. By extending the TestListenerAdapter class, you can override the methods to add custom behavior to your tests. The following are the methods of ITestListener interface that can be overridden in TestListenerAdapter:

  1. onTestStart: This method is called before a test method starts.

  2. onTestSuccess: This method is called after a test method has successfully completed.

  3. onTestFailure: This method is called after a test method has failed.

  4. onTestSkipped: This method is called after a test method has been skipped.

  5. onTestFailedButWithinSuccessPercentage: This method is called after a test method has failed, but within the success percentage set by the "successPercentage" attribute in the @Test annotation.

By using TestListenerAdapter, you can add custom behavior to your tests, such as logging test results, taking screenshots, or updating a database. To use TestListenerAdapter, you must extend the TestListenerAdapter class and register it as a TestNG listener. Here is an example of how to use TestListenerAdapter in TestNG
public class TestListener extends TestListenerAdapter { @Override public void onTestSuccess(ITestResult result) { // Custom code to run after a test method has successfully completed } @Override public void onTestFailure(ITestResult result) { // Custom code to run after a test method has failed } }
In your testng.xml file, you can register the listener by adding the following code:
<listeners> <listener class-name="com.example.TestListener"/> </listeners>

16. How to ignore packages and classes. 

To ignore packages and classes in TestNG, you can use the "exclude" and "include" attributes in the <suite> tag in the testng.xml file. The "exclude" attribute specifies the packages and classes that should be excluded from the test run, and the "include" attribute specifies the packages and classes that should be included in the test run.

Here is an example of how to exclude a package from the test run in TestNG:

<suite name="My Suite"> <test name="My Test"> <classes> <class name="com.example.*" exclude="com.example.IgnoredPackage.*"/> </classes> </test> </suite>

In this example, all classes in the "com.example" package will be included in the test run, except for classes in the "com.example.IgnoredPackage" package.

Here is an example of how to include specific classes in the test run in TestNG:

<suite name="My Suite"> <test name="My Test"> <classes> <class name="com.example.IncludedClass1"/> <class name="com.example.IncludedClass2"/> </classes> </test> </suite>

<suite name="My Suite">
  <test name="My Test">
    <classes>
      <class name="com.example.IncludedClass1"/>
      <class name="com.example.IncludedClass2"/>
    </classes>
  </test>
</suite>
In this example, only the classes "com.example.IncludedClass1" and "com.example.IncludedClass2" will be included in the test run. All other classes in the "com.example" package will be excluded.

17. Can user provide negative value for setting priority.

Ans)Yes

18)What is the main use of @listener annotation in TestNG?

The @Listener annotation in TestNG is used to specify a custom TestNG listener class, which allows you to extend TestNG's behavior. The listener class listens to the events triggered by TestNG during the test run and allows you to customize TestNG's behavior.

19)can We frame html and xml reports for testng for viewing the test results?

Yes, you can generate HTML and XML reports for TestNG for viewing test results. TestNG provides built-in support for generating reports in both HTML and XML formats, which provide a summary of the test results, including information on test cases that passed, failed, or were skipped. You can also customize these reports to include additional information, such as the output of test methods, the parameters used in test cases, and the time taken by each test case.

20)What are different ways to execute parallel tests in selenium?

Ans)Executing parallel tests in Selenium is a valuable technique to save time and run tests more efficiently. Selenium provides several methods to execute tests in parallel. Here are some of the most commonly used approaches:

1)TestNG Parallel Test Execution:

  • TestNG is a testing framework that natively supports parallel test execution.
  • You can use TestNG's parallel attributes (parallel, thread-count, and data-provider-thread-count) to specify parallel execution configurations.
  • TestNG allows you to run test methods, classes, or suites in parallel.
2)JUnit Parallel Execution:
  • JUnit 5 also supports parallel test execution.
  • You can use JUnit 5's @Execution annotation to specify execution modes (e.g., CONCURRENT, SAME_THREAD) for test classes and methods.
  • JUnit 4, while not natively supporting parallelism, can be combined with custom solutions like JUnit Parallel Runner.
3)Using Selenium Grid:
  • Selenium Grid is a powerful tool for parallel test execution across multiple nodes (machines).
  • It allows you to distribute test execution across different browsers, operating systems, and devices.
  • You can set up a Selenium Grid hub and multiple nodes to run tests in parallel.
4)Parallel Browsers with WebDriver:
  • If you want to run tests in parallel on a single machine, you can create multiple instances of WebDriver (one for each thread) and run tests concurrently.
  • You need to manage synchronization and thread safety when using this approach.
5)Docker Containers:
  • You can use Docker containers to parallelize your tests.
  • Each container can run a separate instance of your testing environment, allowing for parallel execution.
  • Docker Swarm or Kubernetes can be used for orchestration.
6)CI/CD Pipelines:
  • Many CI/CD (Continuous Integration/Continuous Deployment) tools support parallel test execution.
  • You can configure parallelism settings in your CI/CD pipeline to distribute tests across multiple agents or runners.
7)Third-Party Tools:
  • Some third-party tools and testing platforms offer built-in support for parallel test execution.
  • These tools often provide a user-friendly interface for configuring and managing parallelism.
8)Custom Solutions:
  • For more complex scenarios, you can implement custom parallel test execution solutions using multi-threading or parallel processing libraries.
  • Be cautious with thread synchronization and resource management when using custom solutions.
When implementing parallel test execution, consider factors like test dependencies, resource allocation, reporting, and thread safety. Also, ensure that your application and tests are compatible with parallel execution, as some applications may have limitations or issues when subjected to concurrent testing.

21)How to execute different suites using Maven and TestNG? 

Ans)Executing different TestNG suites using Maven is a common practice in test automation to manage and organize your tests effectively. You can define multiple TestNG suite XML files and use Maven to execute them selectively. Here's how you can do it:

Create TestNG Suite XML Files:

  • First, create separate TestNG suite XML files for each suite you want to run. These XML files define which test classes and methods are included in each suite.

Example suite1.xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite1"> <test name="Test1"> <classes> <class name="com.example.TestClass1" /> <!-- Add more test classes here --> </classes> </test> </suite>


Example suite2.xml:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite2"> <test name="Test2"> <classes> <class name="com.example.TestClass2" /> <!-- Add more test classes here --> </classes> </test> </suite>

Configure the Maven POM File:

  • In your Maven project, configure the pom.xml file to include the TestNG plugin and specify which suite XML files to run.
  • Use the suiteXmlFiles configuration in the maven-surefire-plugin to specify the suite XML files you want to execute.
<project>
    ...
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version> <!-- Use the latest version -->
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>suite1.xml</suiteXmlFile>
                        <suiteXmlFile>suite2.xml</suiteXmlFile>
                        <!-- Add more suite XML files here -->
                    </suiteXmlFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>

Run the Suites with Maven:

  • Open a terminal or command prompt.
  • Navigate to your Maven project's root directory.
  • Execute the Maven test goal to run the TestNG suites.
mvn clean test

  1. Maven will execute the specified TestNG suites, and you'll see the test results in the console.

By configuring different suite XML files in your Maven pom.xml file, you can easily organize and execute your tests into logical groups. This approach is particularly useful for running different sets of tests, such as smoke tests, regression tests, or specific feature tests, based on your project's requirements.

How to run TestNG tests in parallel?

How to perform parameterized testing in TestNG?

How to create data-driven tests in TestNG?

How to handle dependencies between test methods in TestNG?

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

How to disable a test method in TestNG?

Explain the use of listeners in TestNG.

How to prioritize test methods execution in TestNG?

What is the purpose of the @DataProvider annotation in TestNG?

How can you perform group-wise execution of test methods in TestNG?

How to handle timeouts in TestNG test methods?

Explain the concept of soft assertions in TestNG.

How to use TestNG data providers with external data sources like Excel or CSV files?

How can you handle test dependencies across classes in TestNG?

How to pass parameters to a TestNG test method from the testng.xml file?

Explain the purpose of the @Factory annotation in TestNG.

How to retry failed tests in TestNG?

What is the purpose of TestNG listeners? Can you provide examples of different types of TestNG listeners?

How can you execute TestNG tests programmatically without using the testng.xml file?

How can you handle test suite configuration or setup in TestNG?

How can you configure test methods to always run even if they are part of a failed group or dependency chain in TestNG?

Explain the use of the @DataProvider and @Factory annotations together in TestNG.

How can you configure TestNG to run tests in a specific order?

How can you perform cross-browser testing using TestNG?

How can you integrate TestNG with Maven for test execution?

How can you configure TestNG to generate HTML test reports?

How can you skip a test method conditionally in TestNG?

How can you perform parallel execution of test methods in TestNG?

How can you configure TestNG to generate reports in different formats?

How can you configure TestNG to run tests based on regular expression patterns?

How can you configure TestNG to run tests with a specific invocation count?

Explain the purpose of the @BeforeSuite and @AfterSuite annotations in TestNG.

How can you configure TestNG to run tests based on groups and priority together?

Explain the purpose of the @Parameters annotation's inheritGroups attribute.

How can you configure TestNG to run tests in a specific order using the preserve-order attribute in the testng.xml file?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.