Introduction to TestNG Annotations
Introduction to TestNG Annotations
TestNG is a powerful testing framework inspired by JUnit and NUnit, designed for test configuration, execution, and reporting in Java. One of its key features is the use of annotations to control test flow. These annotations help define how and when specific test methods should be executed.
What Are Annotations in TestNG?
Annotations in TestNG are special tags that control the behavior of test methods. They are defined using the @ symbol followed by the annotation name and are placed above method definitions in your test class.
Commonly Used TestNG Annotations
Here are some of the most frequently used TestNG annotations:
Annotation Description
@Test Marks a method as a test method.
@BeforeMethod Runs before each @Test method.
@AfterMethod Runs after each @Test method.
@BeforeClass Runs once before any @Test methods in the class.
@AfterClass Runs once after all @Test methods in the class.
@BeforeSuite Runs before all tests in the suite.
@AfterSuite Runs after all tests in the suite.
@BeforeTest Runs before any test belonging to the classes inside the <test> tag in TestNG XML.
@AfterTest Runs after all the tests in the <test> tag.
@BeforeGroups Runs before the first test method of a specified group is invoked.
@AfterGroups Runs after the last test method of a specified group is executed.
Example:
java
Copy
Edit
import org.testng.annotations.*;
public class SampleTest {
@BeforeClass
public void setupClass() {
System.out.println("Before Class");
}
@BeforeMethod
public void setupMethod() {
System.out.println("Before Method");
}
@Test
public void testCase1() {
System.out.println("Test Case 1");
}
@Test
public void testCase2() {
System.out.println("Test Case 2");
}
@AfterMethod
public void tearDownMethod() {
System.out.println("After Method");
}
@AfterClass
public void tearDownClass() {
System.out.println("After Class");
}
}
Output:
pgsql
Copy
Edit
Before Class
Before Method
Test Case 1
After Method
Before Method
Test Case 2
After Method
After Class
Benefits of Using TestNG Annotations
Clear structure: Makes tests easier to manage and understand.
Flexible execution: Supports grouping, prioritization, and dependency management.
Automation-ready: Easily integrates with build tools like Maven and CI tools like Jenkins.
Learn Selenium JAVA Course in Hyderabad
Read More
How to Use Assertions in Selenium Tests
Handling Checkboxes and Radio Buttons in Selenium
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment