我有一个测试用例,其中以枚举的形式提供了我的测试数据。喜欢
enum TestTransactions {
TestTransactions(Transaction T1, Transaction T2, String expectedOutput){}
}
在我的Test课上,我必须将其用作:
class Test {
private final static int REPETITION_COUNT = TestTransactions.values().length;
@RepeatedTest(value=REPETITION_COUNT)
private void testAllTransactions(RepetitionInfo info) {
TestTransactions currentTest = TestTransactions.values()[info.getCurrentRepetition()];
logger.info("Executing test for " + currentTest.name());
setExpectationsFor(currentTest);
whenControllerIsCalled();
Assert.assertEquals(currentTest.getExpectedOutput(), result.getBody());
}
}
[此行@RepeatedTest(value=REPETITION_COUNT)
在给出编译错误,提示“属性值必须为常数。”
有什么方法可以实现这一目标?尽管我也尝试在构造函数和静态块内以及在声明期间分配REPETITION_COUNT (declared as final)
,如本示例所示。
您遇到的是Java编译器的约束。除非更改Java语言规范,否则您将无法做自己想做的事情。
[您可以做的是向Jupiter发出功能请求,使其也接受值提供者,例如类型为Class<? extends Supplier<Integer>>
。或者,您可以使用Jupiter的动态测试功能对其进行仿真。
如果我正确理解了您的用例,那么您想将@ParameterizedTest
与@EnumSource
而不是@RepatedTest
一起使用-这就是JUnit5开箱即用地支持您的用例的方式。
首先,添加对org.junit.jupiter:junit-jupiter-params
的依赖关系(它提供对@ParameterizedTest
的支持),然后:
class Test {
@ParameterizedTest
@EnumSource
void testAllTransactions(TestTransactions currentTest) {
logger.info("Executing test for " + currentTest.name());
setExpectationsFor(currentTest);
whenControllerIsCalled();
Assert.assertEquals(currentTest.getExpectedOutput(), result.getBody());
}
}