Showing posts with label Automation Testing with TestNG. Show all posts
Showing posts with label Automation Testing with TestNG. Show all posts

Priority in TestNG

 




What is priority in TestNG?

In TestNG, the priority attribute is used to define the order of execution of test methods in a class.

By default, TestNG executes test methods in alphabetical order of method names (not the order they appear in the code). If you want to control the execution order explicitly, you can assign a priority to each @Test method.


Key Points about priority:

  • The lower the priority number, the earlier the method will run.

  • priority = 0 will run before priority = 1, and so on.

  • If no priority is specified, TestNG assigns it a default priority of 0.

  • You can assign negative values as well.

  • If two or more tests have the same priority, they run in alphabetical order.



Example Java Code for Priority in TestNG

import org.testng.annotations.Test;

public class PriorityExample {

    @Test(priority = 1)
    public void testC() {
        System.out.println("Test C - Priority 1");
    }

    @Test(priority = 0)
    public void testA() {
        System.out.println("Test A - Priority 0");
    }

    @Test(priority = 2)
    public void testB() {
        System.out.println("Test B - Priority 2");
    }

    @Test  // No priority mentioned, default is 0
    public void testD() {
        System.out.println("Test D - Default Priority (0)");
    }
}




Output:

Test A - Priority 0
Test D - Default Priority (0)
Test C - Priority 1
Test B - Priority 2




Important points:

testA() and testD() both have priority 0. Since testA() comes alphabetically before testD(), it runs first.

Priorities help in defining explicit flow of tests, especially in dependent or staged testing scenarios.

In TestNG, when multiple test methods have the same priority, TestNG does not guarantee any specific execution order among them. It means that the methods with the same priority may be executed in any order, and this order can change across different runs.

Lower priority value = executed earlier

Same priority value = no guaranteed order among those methods



Example Code: Same Priority Test Methods

import org.testng.annotations.Test;

public class SamePriorityExample {

    @Test(priority = 1)
    public void testA() {
        System.out.println("Test A - Priority 1");
    }

    @Test(priority = 1)
    public void testB() {
        System.out.println("Test B - Priority 1");
    }

    @Test(priority = 1)
    public void testC() {
        System.out.println("Test C - Priority 1");
    }

    @Test(priority = 0)
    public void testD() {
        System.out.println("Test D - Priority 0");
    }
}




Output:

Test D - Priority 0
Test A - Priority 1
Test B - Priority 1
Test C - Priority 1




Another Run Might Give:

Test D - Priority 0
Test C - Priority 1
Test A - Priority 1
Test B - Priority 1



If multiple test methods share the same priorityTestNG may run them in any order. So, do not rely on order of execution if you assign the same priority to multiple test methods.

Parameterization in TestNG

  

What is Parameterization in TestNG?

Parameterization in TestNG allows us to run the same test with different sets of data. It helps in data-driven testing, where test data is separated from the test logic. TestNG provides multiple ways to do this, mainly:

  • @Parameters annotation (via testng.xml)
  • @DataProvider annotation (method-based)

1. Using @Parameters (from XML)
Pass parameters directly from the testng.xml file to your test methods.


Steps for Parameterization in TestNG

  • Define parameters in testng.xml

  • Use @Parameters in the test method

  • Use @BeforeMethod or @Test to access them



Java Code for parameterization in TestNG

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterExample {

    @Test
    @Parameters({"username", "password"})
    public void loginTest(String user, String pass) {
        System.out.println("Username: " + user);
        System.out.println("Password: " + pass);
    }
}



testng.xml:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="LoginTest">
    <parameter name="username" value="admin" />
    <parameter name="password" value="admin123" />
    <classes>
      <class name="ParameterExample" />
    </classes>
  </test>
</suite>



2. Using @DataProvider

We can pass multiple sets of data to a test method from a @DataProvider method.


Below is the Java Code for @DataProvider in TestNG:

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExample {

    @Test(dataProvider = "loginData")
    public void loginTest(String username, String password) {
        System.out.println("Testing with Username: " + username + ", Password: " + password);
    }

    @DataProvider(name = "loginData")
    public Object[][] getData() {
        return new Object[][] {
            {"admin", "admin123"},
            {"user", "user123"},
            {"guest", "guest123"}
        };
    }
}

TestNG Dependent Tests

 

What Are Dependent Tests in TestNG?

TestNG allows you to create test dependencies, meaning you can specify that:

  • A test method depends on another method or group

  • If the depended method fails, is skipped, or is not run, the dependent method will also be skipped



Types of Dependencies in TestNG

TypeAnnotation AttributeDescription
Method DependencydependsOnMethodsTest method runs only if other method(s) pass
Group DependencydependsOnGroupsTest method runs only if group(s) pass



If a test case execution depends upon successful execution of other test cases, then in this condition we can use attribute 'dependsOnMethods' in @Test annotation.


Example Java Code for method dependency

import org.testng.annotations.Test;

public class DependentTestExample {

    @Test
    public void launchApp() {
        System.out.println("App launched successfully.");
    }

    @Test(dependsOnMethods = "launchApp")
    public void login() {
        System.out.println("Logged in successfully.");
    }

    @Test(dependsOnMethods = {"login"})
    public void searchProduct() {
        System.out.println("Product searched successfully.");
    }

    @Test(dependsOnMethods = {"searchProduct"})
    public void logout() {
        System.out.println("Logged out successfully.");
    }
}



Output

App launched successfully.
Logged in successfully.
Product searched successfully.
Logged out successfully.

Note: If a Test Fails then searchProduct() and logout() will be skipped.


Example Java Code for group dependency

import org.testng.annotations.Test;

public class GroupDependencyExample {

    @Test(groups = "database")
    public void connectToDB() {
        System.out.println("✔ Database connected.");
    }

    @Test(groups = "database")
    public void fetchData() {
        System.out.println("✔ Data fetched from DB.");
    }

    @Test(dependsOnGroups = "database")
    public void generateReport() {
        System.out.println("✔ Report generated using DB data.");
    }
}




Optional Attributes

AttributeDescription
alwaysRun = trueRun test even if dependency fails
enabled = falseDisable the test
dependsOnMethodsDeclare method dependencies
dependsOnGroupsDeclare group dependencies




Example of attribute: alwaysRun

@Test(dependsOnMethods = "login", alwaysRun = true)
public void sendEmail() {
    System.out.println("Email sent (even if login fails).");
}

TestNG Suite

Creating a TestNG Test Suite allows you to group and run multiple test classes, groups, or methods together using an XML configuration file. This is very useful for organizing your tests logically and controlling test execution.


What is a TestNG Test Suite?

Test Suite is defined in an XML file generally named as 'testng.xml'. It can:

  • Include multiple test classes

  • Run specific methods or groups

  • Control execution order

  • Pass parameters to tests


Below are the steps to create a TestNG Suite

Step 1: Create Your Test Classes


LoginTest.java

import org.testng.annotations.Test;

public class LoginTest {

    @Test
    public void loginWithValidUser() {
        System.out.println("✔ Login with valid user executed.");
    }

    @Test
    public void loginWithInvalidUser() {
        System.out.println("✔ Login with invalid user executed.");
    }
}



HomePageTest.java

import org.testng.annotations.Test;

public class HomePageTest {

    @Test
    public void checkTitle() {
        System.out.println("✔ Home page title check executed.");
    }

    @Test
    public void checkProfileButton() {
        System.out.println("✔ Profile button check executed.");
    }
}



Step 2: Create the testng.xml Test Suite File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite">

    <test name="Login Tests">
        <classes>
            <class name="LoginTest"/>
        </classes>
    </test>

    <test name="Home Page Tests">
        <classes>
            <class name="HomePageTest"/>
        </classes>
    </test>

</suite>


Save testng.xml file in the root of your project (or src/test/resources/ for Maven).

Step 3: Run the Test Suite

In Eclipse or IntelliJ:

  • Right-click on testng.xml

  • Select Run As > TestNG Suite