Search code examples
javacsvtestngtest-datatestng-dataprovider

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.


Solution

  • 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);
        }
    }