DataProvider in TestNG

  

What is @DataProvider in TestNG?

@DataProvider is a feature in TestNG that allows you to run the same test method multiple times with different sets of data. This is a powerful way to implement data-driven testing.


Points to be Remember:

  • It's a method that returns a 2D Object array (Object[][])

  • Each row is treated as a separate invocation of the test method

  • It is linked to a @Test method using the dataProvider attribute

  • You can name it using @DataProvider(name = "myProvider")


Example Code Using @DataProvider

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

public class DataProviderDemo {

    // Test method using data from the DataProvider
    @Test(dataProvider = "loginData")
    public void loginTest(String username, String password) {
        System.out.println("Login with Username: " + username + ", Password: " + password);
    }

    // DataProvider method
    @DataProvider(name = "loginData")
    public Object[][] getData() {
        return new Object[][] {
            {"admin", "admin123"},
            {"user1", "pass1"},
            {"guest", "guest123"}
        };
    }
}


Output:

Login with Username: admin, Password: admin123
Login with Username: user1, Password: pass1
Login with Username: guest, Password: guest123



Why Use @DataProvider?

FeatureDescription
ReusabilityOne DataProvider can serve multiple test methods
FlexibilityData can be fetched from arrays, DB, Excel, etc.
Automation CoverageEasily test edge cases and large data sets



Using Multiple Parameters

You can return multiple types and parameters as needed:

@DataProvider(name = "userData")
public Object[][] getUserData() {
    return new Object[][] {
        {"Alice", 25, true},
        {"Bob", 30, false}
    };
}

@Test(dataProvider = "userData")
public void testUser(String name, int age, boolean isActive) {
    System.out.println(name + " | " + age + " | " + isActive);
}

No comments:

Post a Comment