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

血红的双手。 提交于 2021-01-29 06:08:02

问题


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?


回答1:


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



回答2:


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];
    .....
}


来源:https://stackoverflow.com/questions/62750412/how-to-pass-a-input-and-expected-file-name-dynamically-for-beforeall-method-ju

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!