TestNG Annotations : Part 2 - rohitkrbhardwaj09/TestNG_ByRSA GitHub Wiki
Previously, we learned:
-
How to control test case execution using TestNG XML files.
-
Include/Exclude mechanisms for selective execution.
Annotations help control the execution order of methods in TestNG.
Today we explore:
-
@BeforeTest
-
@AfterTest
Imagine this scenario:
-
You're automating a Personal Loan module.
-
You submit loan data, which is reused in next test runs.
-
If data already exists, tests may fail with "data exists" error.
Use @BeforeTest
to clean or reset the data before running any related tests.
Executes once before any test methods in the <test>
block of TestNG XML.
Place in any class part of the test <test>
block.
@BeforeTest
public void cleanDatabase() {
System.out.println("Cleaning up database before tests...");
// Code to clean DB
}
-
Clean up database records
-
Set base URLs for API tests
-
Start Appium server for mobile tests
Executes once after all test methods in the <test>
block.
Can be placed in any relevant class.
@AfterTest
public void teardown() {
System.out.println("I will execute last");
// Clean-up actions: cookies, logs, connections
}
-
Delete cookies (Selenium/Appium)
-
Close API connections
-
Generate reports
<suite name="LoanDepartment">
<test name="PersonalLoan">
<classes>
<class name="Day1"/>
<class name="Day2"/>
<class name="Day4"/>
</classes>
</test>
<test name="CarLoan">
<classes>
<class name="Day3"/>
</classes>
</test>
</suite>
-
@BeforeTest
and@AfterTest
defined inDay1
,Day2
, orDay4
only apply toPersonalLoan
test folder.
-
@AfterTest
will NOT run after entire suite unless it's placed in every test folder.
-
It runs after all tests inside the same
<test>
block only. -
To run actions after entire suite, use
@AfterSuite
(covered in next lecture).
Context | @BeforeTest Use | @AfterTest Use |
---|---|---|
Selenium | Clear data before test run | Delete cookies after test run |
API Testing | Set base URI for REST-assured tests | Close connections |
Mobile (Appium) | Start Appium server | Stop Appium server |
-
@BeforeTest
runs once before all test methods in the specified<test>
block -
@AfterTest
runs once after all test methods in the<test>
block -
Scope is limited to individual
<test>
tag in XML -
Place cleanup/setup logic in these methods to manage test environments effectively
We will explore:
-
@BeforeSuite
-
@AfterSuite
To handle setup/teardown tasks across the entire test suite.
Stay tuned!