我需要编写一个需要设置和实际测试数据的测试。 简化的代码如下:
//given config and test data
purchase_configs.add(pc1);
purchase_configs.add(pc2);
sales_configs.add(sc1);
sales_configs.add(sc2);
input_value = ....
expectd_value = ....
//when
result = calculate(purchase_configs, sales_configs, input_value)
//then
assertEquals(expected_value, result)
事实上配置和输入值非常复杂,所以我想将它们外部化到一个/多个文件中,例如使用
@CSVFileValue
除了参数之外,测试逻辑是相同的。
问题是购买和销售配置的数量可能会有所不同。有时是 pc1、pc2,有时只有 pc1,有时没有,有时更多。销售也一样。
我知道我可以编写多个测试 - 每个配置数量一个,但似乎很难看。 我知道我可以使用 @MethodSource 并生成参数的变量列表,但是我需要编写所有代码来解析 CSV/JSON 或任何文件,或者有大量 Java 代码来手动创建对象(如果可能的话)仅外部化重要/有意义的参数,其余所有参数都可以使用一些默认/计算值,以免降低可读性。
有没有什么聪明的方法可以使用 junit @ParametrizedTest 来实现拥有一个带参数的测试方法的目标,并且如果可能的话不需要自己创建文件的读取器和解析器?
你可以吗
@Test
void testScenario1() {
assertCalculation(
"input1.json",
List.of("purchaseConfig1.json", "purchaseConfig2.json"),
List.of("salesConfig1.json", "salesConfig2.json"),
"expected1.json"
);
}
@Test
void testScenario2() {
assertCalculation(
"input2.json",
List.of("purchaseConfig3.json", "purchaseConfig4.json"),
List.of("salesConfig3.json", "salesConfig4.json"),
"expected2.json"
);
}
private void assertCalculation(
String inputPath,
List<String> purchaseConfigPaths,
List<String> salesConfigPaths,
String expectedPath
) {
Input input = objectMapper.readValue(..., Input.class);
PurchaseConfig[] purchaseConfigs = objectMapper.readValue(..., PurchaseConfig[].class);
SalesConfig[] salesConfigs = objectMapper.readValue(..., SalesConfig[].class);
Result result = someService.calculate(purchaseConfigs, salesConfigs, input);
String resultJson = objectMapper.writeValueToString(result);
assertThat(resultJson).isEqualTo(...);
}