1

I am using TestNG framework for my unit tests. Using DataProvider annotation, I am able to successfully pass input data from a CSV file to the test method.

The problem is I have several test methods in my test class, each requiring a different dataset as input for testing. All the inputs are present in a single csv file. I know I can specify a single input file by using the DataProvider annotation at class level. However, is there any way that each test case within the test file be run by using only specific data from the input CSV file?

Just to be more clear, my Test Class (say TestDemo) will have 3 test methods (say test1, test2, test3). There is a single CSV file with the test data for all 3 methods. Is there anyway I can specify this as the input file but run each test only with the data intended for that test?

Thanks in advance.

Revansha
  • 1,923
  • 4
  • 16
  • 21

2 Answers2

1

I use Apache Metamodel to read the .CSV file within the @DataProvider method and return the 2-d array. Pretty simple.

I wrote an example of doing it here, using TestNG, of course. Specifically, this class .

Keep in mind that if you put all items in a spreadsheet row into a Object[], then you can pass it straight to your test method as a single object and also, the @BeforeMethod is able to access that row data before your actual test even starts. That is something that JUnit 4.x cannot do.

djangofan
  • 28,471
  • 61
  • 196
  • 289
  • 1
    @GaSacchi MetaModel, being an Apache project, inherits performance characteristics from existing `Open CSV` reader project. Here is the POM: https://github.com/apache/metamodel/blob/master/csv/pom.xml . Here is performance data: https://github.com/uniVocity/csv-parsers-comparison – djangofan Jun 30 '16 at 17:51
  • Thanks. I opted for github.com/monitorjbl/excel-streaming-reader and seems to work well so far.. – Gabe Jun 30 '16 at 18:02
0

TestNG does not support this out of the box but you should be able to easily adapt it. e.g.:

public class TestDemo {
    private static Object[][] data() {
        /* Your original data provider code that returns test data for each test method.
         * You may wish to cache the result using memoization to avoid reading the CSV file
         * multiple times. */
    }

    @DataProvider(indices = 0)
    public static Object[][] data1() {
        return data();
    }

    @Test(dataProvider = "data1")
    public void test1(/* test 1 data parameters */) {
        /* test 1 code */
    }

    @DataProvider(indices = 1)
    public static Object[][] data2() {
        return data();
    }

    @Test(dataProvider = "data2")
    public void test2(/* test 2 data parameters */) {
        /* test 2 code */
    }

    @DataProvider(indices = 2)
    public static Object[][] data3() {
        return data();
    }

    @Test(dataProvider = "data3")
    public void test3(/* test 3 data parameters */) {
        /* test 3 code */
    }
}
mfulton26
  • 29,956
  • 6
  • 64
  • 88