This is a simple Testng script which print message before and after tests and run two test methods using Testng annotations.
Step 1: Project Structure
You can create this in Eclipse, IntelliJ, or any Java IDE.
MyTestNGProject/
├── testng.xml
└── src/
└── MyFirstTest.java
Step 2: Add TestNG to Project
If using Maven, add this to pom.xml
:
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <!-- Latest version --> <scope>test</scope> </dependency> </dependencies>
Step 3: Java Code –
MyFirstTest.java
import org.testng.annotations.*;
public class MyFirstTest {
@BeforeClass
public void setup() {
System.out.println("Setting up before running any test...");
}
@Test
public void testLogin() {
System.out.println("Running test: Login functionality");
}
@Test
public void testLogout() {
System.out.println("Running test: Logout functionality");
}
@AfterClass
public void tearDown() {
System.out.println("Cleaning up after all tests...");
}
}
Explanation of Code
@BeforeClass:
Runs once before any @Test
method in this class. Used to initialize resources.@Test: Marks a method as a test case. TestNG will automatically detect and run it.
@AfterClass: Runs once after all
@Test
methods have run. Used to clean up resources.Step 4: Create T
estng.xml
FileThis file tells TestNG which classes to run.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="MyFirstTestSuite"> <test name="SimpleTest"> <classes> <class name="MyFirstTest"/> </classes> </test> </suite>
Step 5: Run the Test
How to Run in Eclipse/IntelliJ:
Right-click
testng.xml
Choose Run As → TestNG Suite
Output
Setting up before running any test... Running test: Login functionality Running test: Logout functionality Cleaning up after all tests...