Debugger
Debugger

Reputation: 792

How to pass a Input and Expected file name dynamically for BeforeAll Method | Junit 5

I have Implemented a test cases to check the Input and expected Json files are same.

 @BeforeAll
        static void setUp() throws IOException {
            inputList = readInput(CommonTestConstants.FilePath + "/Input1.json");
            expectedList = readExpected(CommonTestConstants.FilePath + "/Expected1.json");
            assertEquals("Checking size of both list",
                    inputList.size(), expectedList.size());
        }



static Stream<Arguments> Arguments() {
        return IntStream.range(0, inputList.size())
                .mapToObj(i -> Arguments.of(inputList.get(i), expectedList.get(i)));
    }


@ParameterizedTest
    @DisplayName("Parameterized Test For First Input")
    @MethodSource("Arguments")
    void testFact(Object object, ExpectedObject expected) throws Exception {
        Outcome outcome = processExpectedJson(object);
        assertEquals(expected, outcome);
    }

For passing the different file names, I have created new test classes and test methods similar like above. It's working as expected. For better configuration now I planned to achieve it in single class. By passing input and expected Json different files dynamically like Input2.json Expected2.json from the single class.

I need to pass each file names as a parameter to BeforeAll method(Like looping), similar to a parameterized test.

Any one can advise to achieve this?

Upvotes: 0

Views: 1045

Answers (2)

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

Use ParameterizedTest as follows:

@ParameterizedTest
@ValueSource(strings = {"inputFile1:expectedResults1", "inputFile2:expectedResults2"})
void checkIdentical(String files) {
    String[] x = files.split(":");
    String inputFile = x[0];
    String expectedResult = x[1];
    .....
}

Upvotes: 2

DaveH
DaveH

Reputation: 7335

I'm not sure why you are implementing that test in a @BeforeAll method.

I'd be tempted to make that method a private method that takes two arguments ( inputFile, expectedResultsFile ) and then write tests that called that method

Something like

@Test
public void test1(){
   checkFilesIdentical("inputFile1", "expectedResults1")
}

@Test
public void test1(){
   checkFilesIdentical("inputFile2", "expectedResults2")
}

private void  checkFilesIdentical( String inputFileName, String expectedResulsFileName ) throws IOException {
    inputList = readInput(CommonTestConstants.FilePath + "/" + inputFileName +"json");
    expectedList = readExpected(CommonTestConstants.FilePath + "/" + expectedResulsFileName + " .json");
    assertEquals("Input and outcome fact lists must be of the same size",
            inputList.size(), expectedList.size());
}

Upvotes: 2

Related Questions