首页 > 解决方案 > 如何在 Junit 5 中动态传递多个输入和输出测试文件名?

问题描述

我需要将多个文件一个一个地传递给下面的 BeforeAll 方法。我可以通过重复相同代码的不同测试类来实现它。我想使用单个类对其进行优化。

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

任何人请建议实现这一目标?

参考 如何为 BeforeAll 方法动态传递输入和预期文件名 | 六月 5

标签: javaspring-bootunit-testingjunitjunit5

解决方案


您可以创建一个Map文件名,然后按如下方式对其进行迭代,

Map<String, String> files = Map.of("/Input1.json", "/Expected1.json",
                                    "Input1.json", "/Expected2.json");

files.forEach((k,v)->{
    inputList = readInput(CommonTestConstants.FilePath + k);
    expectedList = readExpected(CommonTestConstants.FilePath + v);
    assertEquals("Checking size of both list",
            inputList.size(), expectedList.size());
});

推荐阅读