【问题标题】:How to pass a Input and Expected file name dynamically for BeforeAll Method | Junit 5如何为 BeforeAll 方法动态传递输入和预期文件名六月 5
【发布时间】:2020-07-06 06:31:11
【问题描述】:

我已经实现了一个测试用例来检查输入和预期的 Json 文件是否相同。

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

为了传递不同的文件名,我创建了类似上面的新测试类和测试方法。它按预期工作。现在为了更好的配置,我计划在单节课中实现它。通过从单个类动态传递输入和预期的 Json 不同文件,例如 Input2.json Expected2.json

我需要将每个文件名作为参数传递给BeforeAll方法(Like looping),类似于参数化测试。

任何人都可以建议实现这一目标?

【问题讨论】:

    标签: java unit-testing junit junit5 parameterized


    【解决方案1】:

    我不确定您为什么要在 @BeforeAll 方法中实施该测试。

    我很想将该方法设为一个私有方法,它接受两个参数(inputFile、expectedResultsFile),然后编写调用该方法的测试

    类似

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

    【讨论】:

    • 谢谢戴夫。有关详细信息。我正在使用参数化测试方法来比较输入对象和期望对象。如果我正在创建单个测试方法 - 我不确定如何将单个测试返回给 @ParameterizedTest 函数。
    【解决方案2】:

    如下使用ParameterizedTest

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

    【讨论】:

    • @谢谢 Dakshinamurthy。我的逻辑完全不同。我刚刚用我的完整实施更新了我的问题。
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2019-09-07
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多