> For the complete documentation index, see [llms.txt](https://qatesting.gitbook.io/qa/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://qatesting.gitbook.io/qa/automation-testing/flow/selenium/testing-frameworks/testng.md).

# TestNG

## 💡 What is TestNG?

**TestNG is an&#x20;**<mark style="background-color:orange;">**open source automated testing framework**</mark>**&#x20;for Java.** It is designed to cover a wide range of test categories like unit, functional, end-to-end, integration, etc. TestNG is more powerful and flexible than the older JUnit framework.

## Types of Testing Used with TestNG

#### 🧪 Unit Testing

* TestNG is well-suited for writing and managing unit tests to test individual classes, methods, and functions.
* It's annotations like @Test, @BeforeMethod, @AfterMethod etc. make it easy to organize unit tests.

#### 👪 Integration Testing

* TestNG allows you to create test suites that cover interaction between modules/services. This helps in integration testing.
* Dependencies between test methods can be defined for testing workflows.

#### 💻 Functional Testing

* TestNG can be used for functional testing of applications to validate that features and end-to-end workflows work as expected.
* Data providers help parameterize tests with different test data.

#### ☁️ Acceptance Testing

* TestNG combined with Selenium can be used for customer acceptance testing to validate software against customer requirements.

#### 📱 Cross Browser Testing

* TestNG integrates well with Selenium to enable running tests across browsers and platforms for cross browser testing.

#### 🎯 Regression Testing

* Test suites with a stable set of tests can be rerun using TestNG to catch any regressions during software changes.

## 👥 Parallel Testing in TestNG

**Parallel Attribute**

TestNG allows parallel execution of tests by using the 'parallel' attribute in the testng.xml file.

For example:

```xml
<suite name="MySuite" parallel="tests">
```

This runs all the test tags defined in the suite in parallel.

**Thread Count**

The thread-count attribute can specify how many threads to use for concurrent test execution.

For example:

```xml
<suite name="MySuite" parallel="tests" thread-count="5"> 
```

This will use 5 threads to run the tests in parallel.

**Grouping Tests**

Tests can be grouped logically and each group can run in parallel.

For example:

```xml
<test name="Group1Tests">
   <classes>
     <class name="TestClass1"/>
     <class name="TestClass2"/>
   </classes>
</test>

<test name="Group2Tests">
   <classes>
     <class name="TestClass3"/>
     <class name="TestClass4"/>
   </classes>
</test>
```

Here, TestClass1 and TestClass2 will run in parallel as part of Group1. Similarly, TestClass3 and TestClass4 will run parallel in Group2.

**Parallel Modes**

TestNG has different parallel modes like tests, classes, instances etc. We can choose the parallelism at suite, test or class level.

So in summary, TestNG provides annotations, thread pools, grouping and parallel modes to easily enable parallel test execution and reduce test time.

## TestNG Annotations

**@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.

**@BeforeTest**: The annotated method will be run before any test method belonging to the classes inside the tag is run.

**@AfterTest**: The annotated method will be run after all the test methods belonging to the classes inside the tag have 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.

**@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.

**@BeforeMethod**: The annotated method will be run before each test method.

**@AfterMethod**: The annotated method will be run after each test method.

**@Test**: The annotated method is a part of a test case

## 🚦 Test Method Priority in TestNG

**Default Priority**

❗️If test priority is not defined while running multiple test cases, **TestNG assigns all @Test a priority as zero (0).**

🏃‍♂️Now, while running; **lower priorities will be scheduled first.**

💡If we don’t mention any priority, **testng will execute the @Test methods based on alphabetical order of their method names** irrespective of their place of implementation in the code.

## 🥇 Methods with Same Priority

😅There may be a chance that methods may contain same priority.

🔀In those cases, **testng considers the alphabetical order of the method names whose priority is same.**

So in summary:

* Default priority is 0 if not specified
* Lower priority tests run first
* Alphabetical order for same priority tests

This helps organize test execution order in TestNG based on priority and naming conventions.

## What are TestNG Assertions? 🧪

In TestNG, assertions are validations or checkpoints used to verify the expected behavior of an application during automated testing. Assertions help testers determine whether the test cases have passed or failed confidently.

## Types of TestNG Assertions 📚

### Hard Assertions 💪

Hard assertions in TestNG are used to validate the expected result of a test case. If a hard assertion fails, the test execution is aborted, and the test case is marked as failed.

### Soft Assertions (Verify Method) 🌟

Soft assertions in TestNG allow the test execution to continue even if an assertion fails. The test case execution continues till the end, and the results of all assertions are captured. To view the assertions result at the end of the test, the `assertAll()` method needs to be invoked.

<table data-full-width="true"><thead><tr><th>Assertion</th><th>Explanation</th><th>Rules</th><th>Hard/Soft</th></tr></thead><tbody><tr><td><code>assertEquals()</code></td><td>Checks if two values are equal.</td><td>The actual and expected values must be of the same data type.</td><td>Hard</td></tr><tr><td><code>assertNotEquals()</code></td><td>Checks if two values are not equal.</td><td>The actual and expected values must be of the same data type.</td><td>Hard</td></tr><tr><td><code>assertTrue()</code></td><td>Checks if a boolean value is true.</td><td>The actual value must be a boolean.</td><td>Hard</td></tr><tr><td><code>assertFalse()</code></td><td>Checks if a boolean value is false.</td><td>The actual value must be a boolean.</td><td>Hard</td></tr><tr><td><code>assertNull()</code></td><td>Checks if a value is null.</td><td>The actual value must be null.</td><td>Hard</td></tr><tr><td><code>assertNotNull()</code></td><td>Checks if a value is not null.</td><td>The actual value must not be null.</td><td>Hard</td></tr><tr><td><code>assertSame()</code></td><td>Checks if two objects refer to the same object.</td><td>The actual and expected values must be of the same data type.</td><td>Hard</td></tr><tr><td><code>assertNotSame()</code></td><td>Checks if two objects do not refer to the same object.</td><td>The actual and expected values must be of the same data type.</td><td>Hard</td></tr><tr><td><code>assertArrayEquals()</code></td><td>Checks if two arrays are equal.</td><td>The actual and expected arrays must be of the same data type and length.</td><td>Hard</td></tr><tr><td><code>softAssert.assertEquals()</code></td><td>Checks if two values are equal.</td><td>The actual and expected values must be of the same data type.</td><td>Soft</td></tr><tr><td><code>softAssert.assertNotEquals()</code></td><td>Checks if two values are not equal.</td><td>The actual and expected values must be of the same data type.</td><td>Soft</td></tr><tr><td><code>softAssert.assertTrue()</code></td><td>Checks if a boolean value is true.</td><td>The actual value must be a boolean.</td><td>Soft</td></tr><tr><td><code>softAssert.assertFalse()</code></td><td>Checks if a boolean value is false.</td><td>The actual value must be a boolean.</td><td>Soft</td></tr><tr><td><code>softAssert.assertNull()</code></td><td>Checks if a value is null.</td><td>The actual value must be null.</td><td>Soft</td></tr><tr><td><code>softAssert.assertNotNull()</code></td><td>Checks if a value is not null.</td><td>The actual value must not be null.</td><td>Soft</td></tr><tr><td><code>softAssert.assertSame()</code></td><td>Checks if two objects refer to the same object.</td><td>The actual and expected values must be of the same data type.</td><td>Soft</td></tr><tr><td><code>softAssert.assertNotSame()</code></td><td>Checks if two objects do not refer to the same object.</td><td>The actual and expected values must be of the same data type.</td><td>Soft</td></tr><tr><td><code>softAssert.assertArrayEquals()</code></td><td>Checks if two arrays are equal.</td><td>The actual and expected arrays must be of the same data type and length.</td><td>Soft</td></tr></tbody></table>

Here's an example of using TestNG assertions in Java, including both hard and soft assertions:

```java
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
import org.testng.annotations.Test;

public class ExampleTest {
  
  @Test
  public void testHardAssertion() {
    int result = Calculator.add(2, 2);
    Assert.assertEquals(result, 4, "Addition failed!");
    Assert.assertTrue(result > 0, "Result is not positive!");
  }
  
  @Test
  public void testSoftAssertion() {
    SoftAssert softAssert = new SoftAssert();
    int result = Calculator.divide(10, 0);
    softAssert.assertNotEquals(result, 0, "Division failed!");
    softAssert.assertTrue(result > 0, "Result is not positive!");
    softAssert.assertAll();
  }
  
}
```

In this example, we have two test methods that use both hard and soft assertions:

* `testHardAssertion()` uses two hard assertions to validate the behavior of the Calculator class.
* `testSoftAssertion()` uses two soft assertions to validate the behavior of the Calculator class. The `assertAll()` method is used to capture all the assertions and report them at the end of the test.

Please note that the `Calculator` class and its methods are not shown in this example. You can replace them with your own class and methods.

## Key differences between TestNG and JUnit

<table data-full-width="true"><thead><tr><th width="138">Feature</th><th>TestNG</th><th>JUnit</th><th>Explanation</th></tr></thead><tbody><tr><td>Annotations</td><td>@Test, @BeforeMethod, @AfterMethod, @DataProvider etc</td><td>@Test, @Before, @After etc</td><td>TestNG uses its own set of annotations to define tests and configuration. JUnit has a different set of annotations.</td></tr><tr><td>Test Fixtures</td><td>Supports setup/teardown at class and method level</td><td>Supports only at class level</td><td>TestNG allows configuring test fixtures at class level using @BeforeClass/@AfterClass and also at method level using @BeforeMethod/@AfterMethod. JUnit only supports class level fixtures.</td></tr><tr><td>Execution Modes</td><td>Supports parallel, sequential, single-threaded modes</td><td>Only sequential execution</td><td>TestNG allows parallel execution of tests across threads. JUnit executes tests sequentially by default.</td></tr><tr><td>Dependencies</td><td>Supports defining dependencies between test methods</td><td>No support for dependencies</td><td>TestNG allows controlling test execution flow by defining dependencies between methods. Missing in JUnit.</td></tr><tr><td>Skipping Tests</td><td>Supports conditional test skipping</td><td>No support</td><td>TestNG allows programmatically skipping tests using ITestResult. Not directly possible in JUnit.</td></tr><tr><td>Parameterization</td><td>Inbuilt support using @DataProvider</td><td>Requires separate libraries</td><td>TestNG has native support for data-driven testing through @DataProvider annotation. JUnit requires separate libs like PITest.</td></tr><tr><td>Grouping</td><td>Allows grouping tests into suites</td><td>No native support</td><td>TestNG allows logically grouping tests into suites. The grouping concept doesn't exist in JUnit.</td></tr><tr><td>Reports</td><td>Generates detailed HTML reports</td><td>Minimal reports</td><td>TestNG produces full detailed test reports. JUnit has basic reporting.</td></tr><tr><td>Assertions</td><td>Custom assertions like Assert.assertTrue()</td><td>Assert.assertEquals() etc</td><td>TestNG has its own set of assertions in org.testng package. JUnit uses org.junit assertions.</td></tr></tbody></table>

In summary, TestNG has more extensive features and flexibility related to test organization, execution, config and reporting.
