如何为不同的输入文件创建 JUnit 测试作为单独的案例?
How to create JUnit tests for different input files as separate cases?
现在,我的解释器有大约 107 个测试输入案例,我的 JUnit 测试器设置为手动独立处理每个案例,以免将它们混为一谈。也就是说,如果我使用循环遍历测试文件
for (int i = 0; i < NUM_TESTS; i++) {
String fileName = "file_" + (i + 1) + ".in";
testFile(fileName);
}
JUnit 将为所有 107 个测试创建一个巨大的测试结果,这意味着如果一个失败,则整个测试都会失败,这是我不希望的。正如我所说,现在我有类似
@Test
public static void test001() {
testFile("file1.in");
}
@Test
public static void test002() {
testFile("file2.in");
}
虽然这可行,但我认为有更好的解决方案来实现我的目标。
您必须根据需要定义自己的结构,
一种定义 json 文件输入的方法,如下所示。
{
[
"value1",
"value2"
]
}
在object mapper
的帮助下执行测试用例时读取此值。
objectMapper.readValue(fixture("filePathName.json"),CustomInput.class);
CustomInput 如下所示。
public class CustomInput {
List<String> values;
}
您可以在 json 中不断增加和减少输入。
您可以将 @ParameterizedTest
与 @MethodSource
注释一起使用。
例如:
@ParameterizedTest
@MethodSource("fileNameSource")
void test(final String fileName) {
testFile(fileName);
}
private static Stream<String> fileNameSource() {
return IntStream.range(0,NUM_TESTS).mapToObj(i -> "file_" + (i + 1) + ".in");
}
在 https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests
查看文档
对于fileNameSource()
返回的每个参数,相应的测试将被视为不同的情况。
现在,我的解释器有大约 107 个测试输入案例,我的 JUnit 测试器设置为手动独立处理每个案例,以免将它们混为一谈。也就是说,如果我使用循环遍历测试文件
for (int i = 0; i < NUM_TESTS; i++) {
String fileName = "file_" + (i + 1) + ".in";
testFile(fileName);
}
JUnit 将为所有 107 个测试创建一个巨大的测试结果,这意味着如果一个失败,则整个测试都会失败,这是我不希望的。正如我所说,现在我有类似
@Test
public static void test001() {
testFile("file1.in");
}
@Test
public static void test002() {
testFile("file2.in");
}
虽然这可行,但我认为有更好的解决方案来实现我的目标。
您必须根据需要定义自己的结构, 一种定义 json 文件输入的方法,如下所示。
{
[
"value1",
"value2"
]
}
在object mapper
的帮助下执行测试用例时读取此值。
objectMapper.readValue(fixture("filePathName.json"),CustomInput.class);
CustomInput 如下所示。
public class CustomInput {
List<String> values;
}
您可以在 json 中不断增加和减少输入。
您可以将 @ParameterizedTest
与 @MethodSource
注释一起使用。
例如:
@ParameterizedTest
@MethodSource("fileNameSource")
void test(final String fileName) {
testFile(fileName);
}
private static Stream<String> fileNameSource() {
return IntStream.range(0,NUM_TESTS).mapToObj(i -> "file_" + (i + 1) + ".in");
}
在 https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests
查看文档对于fileNameSource()
返回的每个参数,相应的测试将被视为不同的情况。