简体   繁体   中英

Java testng single dataprovider multiple test

Scenario: I have a csv file with 10 columns of test data. For each column I want to have a test method.

Now I know how to use dataprovider to read the csv file and provide the test data to a test method. But how can I use the same testprovider for multiple tests?

The dataprovider that I have written for now is reading the csv file and iterating through the csv.

If i understand your question correctly then what you want to do is lets say you have 10 columns and this 10 columns need to be passed to 10 test methods respectively as test data, but you want data provider as same. My recommendation: 1) Pass Method argument to your dataprovider. 2) Load whole CSV file into 2D array. 3) Based on test method name that return that column data as test data for that test. Something like below:

import java.lang.reflect.Method;

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

public class TestNGTest {
    @DataProvider
    public Object[][] dp(Method method)
    {
        System.out.println("Test method : "+method.getName());
        if(method.getName().equals("test1"))
            return new Object[][]{{method.getName()}};
        else if(method.getName().equals("test2"))
            return new Object[][]{{method.getName()}};
        else
            return new Object[][]{};
    }

    @Test(dataProvider="dp")
    public void test1(String name)
    {
        System.out.println("DP -->"+name);
    }

    @Test(dataProvider="dp")
    public void test2(String name)
    {
        System.out.println("DP -->"+name);
    }
}

You can easily declare data provider in separate class and reuse it in multiple classes. Take a look at dataProviderClass parameter of @Test annotation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM