I have a working JUnit test class that uses DataProvider, and in fact reads the tests from files in a directory. The tests have "mock DB" implementation in a way that there are 5 files that are loaded into the memory and the served via the DB interface, and one file that is the "data-provider" (csv with inputs and expected outputs).

tests/table1.csv
..
tests/table5.csv
tests/data-provider.csv

I'd like to change it such a way that I'll be able to add new tests in sub-directories.

tests/1/table1.csv
..
tests/1/table5.csv
tests/1/data-provider.csv

tests/2/table1.csv
..
tests/2/table5.csv
tests/2/data-provider.csv

It should work in such a way that it loads the mock DB in a sub-dir, then runs the tests from the same sub-dir, then resets everything and does the same for the next sub-dir.

What I have (in the comments I added some "subDir" related things, but not sure how can I use them without having to copy&paste both the provider and the test method for each sub-dir manually):

@RunWith(DataProviderRunner.class)
public class MyTest {
    private DataProvider1 dp1;

    private void init(/*String subDir*/) {
      // initialize mocks...
      // load actual data from files to dp1
      dp1 = new DataProvider1();
      dp1.loadFromDir("mytests" /* + "/" + subDir */);
    }

    @DataProvider
    public static Object[][] dataProvider() throws FileNotFoundException, ParseException {
        // load the "static" test data (~ mock data)
        /*String subDir = "1";*/
        init(/*subDir*/);

        // load the tests (input, expected output)
        DataProviderFetcher tests = new DataProviderFetcher();
        preLoadFetcher("mytests" /*+ File.separator + subDir*/ + File.separator + "data-provider.csv", DATA_PROVIDER_PARSER, tests);
        return tests.data.toArray(new Object[0][]);
    }

    @Test
    @UseDataProvider("dataProvider")
    public void testMyCode(String errorMessage, X input, Y expected) throws Exception {
        Y actual = new MyCode().calculate(input);
        assertEquals(errorMessage, expected, actual);
    }

}

0 Answers