First TestNG script

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 EclipseIntelliJ, 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>

If not using Maven:



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

@BeforeClassRuns 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 Testng.xml File

This 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:

  1. Right-click testng.xml

  2. 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...