TestNG Installation

Below are the steps showing how you can install Testng on different popular IDEs that is Eclipse, IntelliJ IDEA, and for use with Maven/Gradle projects.


1. Installing TestNG in Eclipse

Method 1: Using Eclipse Marketplace

  • Open Eclipse.
  • Go to Help → Eclipse Marketplace.
  • In the Find box, type TestNG.
  • Click Go and find TestNG for Eclipse.
  • Click Install, accept the license, and finish.
  • Restart Eclipse.


Verify Installation:

  • Right-click on your project → New → Other → Search for TestNG Class.

  • You should also see a TestNG tab in the menu bar.


2. Installing TestNG in IntelliJ IDEA

Method 1: Enable Built-in Support

  • Open IntelliJ IDEA.
  • Go to File → Project Structure.
  • Select Modules → Dependencies.
  • Click + → Select Library → Choose From Maven.
  • Type: org.testng:testng:7.9.0
  • Click OK to download and add to your project.

Method 2: Add to Maven pom.xml

<dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>7.9.0</version>
  <scope>test</scope>
</dependency>


IntelliJ will auto-download the dependency.

Verify Installation:

  • Right-click a class → Run as TestNG Test.

  • Check Run Configurations → You should see TestNG.


3. Using TestNG with Gradle Projects

Add to build.gradle:

dependencies {
    testImplementation 'org.testng:testng:7.9.0'
}

test {
    useTestNG()
}

Run:

gradle test

TestNG Annotations

 

Testng is a testing framework inspired by JUnit and NUnit, designed for test configuration flexibility and powerful reporting in Java. Annotations in TestNG control how and when test methods are executed.


Common Testng Annotations

AnnotationDescription
@BeforeSuiteRuns once before all tests in the suite
@AfterSuiteRuns once after all tests in the suite
@BeforeTestRuns before <test> tag in TestNG XML file
@AfterTestRuns after <test> tag in TestNG XML file
@BeforeClassRuns before the first method in the current class
@AfterClassRuns after all methods in the current class
@BeforeMethodRuns before each @Test method
@AfterMethodRuns after each @Test method
@TestMarks a method as a test case
@DataProviderProvides data for parameterized tests
@ParametersInjects parameters from XML into test methods
@BeforeGroupsRuns before the first method of the specified group
@AfterGroupsRuns after the last method of the specified group


Example java code of Testng Annotations:

import org.testng.annotations.*;

public class TestNGAnnotationsExample {

    @BeforeSuite
    public void beforeSuite() {
        System.out.println("→ @BeforeSuite: Runs before the entire test suite");
    }

    

    @BeforeTest
    public void beforeTest() {
        System.out.println("→ @BeforeTest: Runs before <test> section in XML");
    }



    @BeforeClass
    public void beforeClass() {
        System.out.println("→ @BeforeClass: Runs before the first method of the class");
    }

   
    @BeforeMethod
    public void beforeMethod() {
        System.out.println("→ @BeforeMethod: Runs before each @Test method");
    }

   

    @Test
    public void testCase1() {
        System.out.println("✔ Running Test Case 1");
    }

    @Test
    public void testCase2() {
        System.out.println("✔ Running Test Case 2");
    }


    @AfterMethod
    public void afterMethod() {
        System.out.println("→ @AfterMethod: Runs after each @Test method");
    }

    @AfterClass
    public void afterClass() {
        System.out.println("→ @AfterClass: Runs after all test methods of the class");
    }

    @AfterTest
    public void afterTest() {
        System.out.println("→ @AfterTest: Runs after <test> section in XML");
    }

    @AfterSuite
    public void afterSuite() {
        System.out.println("→ @AfterSuite: Runs after the entire test suite");
    }
}


Order of Execution of TestNG Annotations

OrderAnnotationExecuted When
1@BeforeSuiteOnce before the entire test suite starts
2@BeforeTestBefore <test> tag in the XML file
3@BeforeGroupsBefore any test method belonging to a specified group
4@BeforeClassBefore the first test method in the current class
5@BeforeMethodBefore each test method (@Test)
6@TestActual test case
7@AfterMethodAfter each test method (@Test)
8@AfterClassAfter all test methods in the current class
9@AfterGroupsAfter all test methods belonging to a specified group
10@AfterTestAfter <test> tag in the XML file
11@AfterSuiteOnce after the entire test suite finishes


Execution Flow of Testng annotations

@BeforeSuite
@BeforeTest
@BeforeGroups
@BeforeClass

@BeforeMethod
@Test
@AfterMethod

@BeforeMethod
@Test
@AfterMethod

@AfterClass
@AfterGroups
@AfterTest
@AfterSuite

Introduction to TestNG

  

What is TestNG?

TestNG stands for Test Next Generation. It is an open-source testing framework inspired by JUnit and NUnit, designed specifically for the Java programming language. It overcomes the limitations of older frameworks by introducing powerful features for unit testing, functional testing, integration testing, and end-to-end testing.


Below are some key features of Testng

  • Annotations:
    TestNG uses a wide variety of annotations (@Test, @BeforeClass, @AfterMethod, etc.) to control test behavior and execution flow.
  • Flexible Test Configuration:
    Allows grouping, prioritization, dependencies, and conditional test execution.
  • Parallel Test Execution:
    You can run multiple tests simultaneously, which reduces total execution time and is useful for large projects.
  • Parameterization:
    TestNG supports both static and dynamic test data through parameters and data providers.
  • Test Suite Execution:
    Tests can be organized into suites using an XML configuration file (testng.xml), allowing you to control test runs from a central place.
  • Powerful Reporting:
    It automatically generates HTML and XML reports after execution, providing insights into test pass/fail status.
  • Integration Support:
    Works well with tools like Maven, Jenkins, Selenium WebDriver, Eclipse, IntelliJ, and various CI/CD tools.
  • Exception Handling:
    It allows defining what exceptions to expect, which helps in testing negative or error-prone scenarios.

Structure of TestNG Testing

  • Test Suite:
    A collection of tests defined in the testng.xml file.
  • Test:
    A test block within a suite. It can include multiple test classes.
  • Test Class:
    Java class containing test methods and configurations.
  • Test Methods:
    Individual test cases.

Test Execution Flow in TestNG

TestNG follows a specific sequence in running methods:

  • BeforeSuite
  • BeforeTest
  • BeforeClass
  • BeforeMethod
  • Test Method
  • AfterMethod
  • AfterClass
  • AfterTest
  • AfterSuite

Types of Testing Supported by TestNG

  • Unit Testing: Test individual components.

  • Functional Testing: Validate business logic.

  • Integration Testing: Test combined modules.

  • Regression Testing: Re-run test cases to ensure no new bugs.

  • Data-Driven Testing: Run same tests with different inputs.


We can use Testng for below scenarios

  • Automating browser testing with Selenium

  • Running API tests

  • Validating database operations

  • Managing large test suites

  • Executing tests in a distributed environment


Tools and Environment Compatibility

  • IDEs: Eclipse, IntelliJ IDEA

  • Build Tools: Maven, Gradle

  • CI/CD Tools: Jenkins, Bamboo

  • Reporting Tools: Allure, ExtentReports

  • Testing Tools: Selenium WebDriver, REST Assured

How to validate Response by Matchers API in Rest Assured

  

How to Use Hamcrest Matchers in GET API via Rest Assured

Hamcrest is a framework for writing matcher objects, which allow 'match' rules to be defined declaratively. In Rest Assured, we use Hamcrest matchers to write expressive assertions for validating the API response.


Maven Dependencies:

<dependencies>
    <!-- Rest Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.0</version>
        <scope>test</scope>
    </dependency>

    <!-- Hamcrest -->
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest</artifactId>
        <version>2.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>




Commonly Used Hamcrest Matchers


MatcherDescription
equalTo(value)Check equality
hasItem(value)Check if a list contains item
hasItems(val1, val2)Check if list contains multiple items
not(value)Asserts the opposite
containsString(str)Check substring match
startsWith(str)Check if string starts with



API to be tested:

https://reqres.in/api/users?page=2




Java Code:

import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class GetApiHamcrestExample {
    public static void main(String[] args) {

        // Set base URI
        RestAssured.baseURI = "https://reqres.in";

        // GET Request with Hamcrest matchers for assertions
        given()
            .log().all()
        .when()
            .get("/api/users?page=2")
        .then()
            .log().all()
            .statusCode(200)
            .body("page", equalTo(2))  // validate page number
            .body("data.id", hasItems(7, 8, 9))  // check if certain user IDs are present
            .body("data.first_name", hasItem("Michael"))  // check first_name list contains value
            .body("support.url", containsString("reqres.in"))  // substring match
            .body("data.email[0]", startsWith("michael"));  // starts with
    }
}



Output:

Request:
GET https://reqres.in/api/users?page=2

Response:
200 OK
...
Assertions:
page == 2
data.id contains 7, 8, 9
data.first_name contains "Michael"
support.url contains "reqres.in"
data.email[0] startsWith "michael"

How to test Preemptive Authentication in Rest Assured

  

What is Preemptive Authentication?

In preemptive authentication, the client sends the credentials (username & password) in the very first request, rather than waiting for the server to challenge it (with a 401 unauthorized response).
This can improve performance by skipping an extra request-response cycle.


To use preemptive basic auth in Rest Assured:

  • Use .auth().preemptive().basic(username, password)
  • This sends the Authorization header directly with the GET request.
  • You can validate response data with assertions.



API to be tested:

https://postman-echo.com/basic-auth

This endpoint requires Basic Authentication

Username: "postman"

Password: "password"



Java Code using Rest Assured:

import io.restassured.RestAssured;
import io.restassured.response.Response;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class PreemptiveAuthTest {

    public static void main(String[] args) {

        // Base URI
        RestAssured.baseURI = "https://postman-echo.com";

        // Preemptive Basic Auth GET Request
        given()
            .auth().preemptive().basic("postman", "password")
        .when()
            .get("/basic-auth")
        .then()
            .statusCode(200)
            .body("authenticated", equalTo(true))
            .log().all();
    }
}




Output:
{
  "authenticated": true
}


Explanation:


LinePurpose
.auth().preemptive().basic(...)Sends credentials proactively without waiting for a challenge
.get("/basic-auth")Executes the GET request
.statusCode(200)Asserts the response status is OK
.body("authenticated", equalTo(true))Asserts that authentication was successful
.log().all()Logs full response details to console




How to test Basic Authentication by using Rest Assured

 

To use Basic Authentication in a GET API via Rest Assured, you need to include the username and password using .auth().basic(username, password) in your request.


What is Basic Authentication?

Basic Auth is an authentication method where:

  • The client sends the username and password encoded in Base64 in the request headers.

  • The format is:

Authorization: Basic Base64(username:password)




API to be tested:

https://postman-echo.com/basic-auth
It requires:

Username: postman

Password: password



Maven Dependency:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>




Full Java Code
import io.restassured.RestAssured;
import io.restassured.response.Response;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class BasicAuthGetAPI {

    public static void main(String[] args) {
        // Set Base URI
        RestAssured.baseURI = "https://postman-echo.com";

        // Send GET request with basic auth
        Response response = given()
                .auth().basic("postman", "password") // Basic Auth
        .when()
                .get("/basic-auth") // GET Endpoint
        .then()
                .statusCode(200) // Check status code
                .body("authenticated", equalTo(true)) // Validate response body
                .extract().response();

        // Print the response
        System.out.println("Response:\n" + response.prettyPrint());
    }
}



Output:
{
  "authenticated": true
}






Code Explanation:


LinePurpose
.auth().basic("postman", "password")Adds Basic Auth credentials
.get("/basic-auth")Performs GET request
.statusCode(200)Asserts HTTP response is OK
.body("authenticated", equalTo(true))Asserts authenticated key is true

How to test Graph QL API in Rest Assured

 

To validate a GraphQL API using Rest Assured in Java, follow these key steps:


Key Concepts

  • GraphQL APIs use a single endpoint (typically /graphql) for all operations.
  • The query or mutation is passed as a JSON payload (usually in the body of a POST request).
  • Response is usually in JSON, and can be validated using JsonPathMatchers, etc.

Public GraphQL API for Example

We'll use the public GraphQL API from https://countries.trevorblades.com/

Endpointhttps://countries.trevorblades.com/
Example Query (returns name and capital of India):



{
  country(code: "IN") {
    name
    capital
  }
}




Java Code Using Rest Assured


import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.json.JSONObject;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class GraphQLApiTest {

    public static void main(String[] args) {

        // GraphQL query as string
        String query = "{ country(code: \"IN\") { name capital } }";

        // Prepare the JSON body
        JSONObject requestBody = new JSONObject();
        requestBody.put("query", query);

        // Set base URI
        RestAssured.baseURI = "https://countries.trevorblades.com/";

        // Send POST request and validate response
        given()
            .header("Content-Type", "application/json")
            .body(requestBody.toString())
        .when()
            .post()
        .then()
            .statusCode(200)
            .body("data.country.name", equalTo("India"))
            .body("data.country.capital", equalTo("New Delhi"));
    }
}



Validations Performed

  • HTTP status code = 200

  • Country name = "India"

  • Capital = "New Delhi"





Maven Dependencies:


<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>