First TestNG script




This is a simple Testng script which print message before and after tests and run two test methods using Testng annotations.

After installation of TestNG in Eclipse or IntelliJ Idea, we need to follow below steps to write TestNG scripts.


Below are the steps of writing first TestNG script.

a) Create a  java class as test class, we can name as MyFirstTest.java

b) Add TestNG dependencies in POM.xml

c) Write TestNG test code in MyFirstTest.java class as mentioned below.

d) We can directly execute code in eclipse or intellij Idea or create a separate TestNG.xml for Test cases execution, as shown below.

e) Right Click on TestNG.xml file and run the file.














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:

  • Right-click testng.xml
  • Choose Run As → TestNG Suite


Output

Test script executed successfully and logs the statements on console.

Setting up before running any test...
Running test: Login functionality
Running test: Logout functionality
Cleaning up after all tests...


Suggested Posts:

1. Read Excel Data by Data provider
2. TestNG Dependent Tests
3. TestNG Asserts
4. Parameterization in TestNG
5. Priority in TestNG