【问题标题】:Can I have variable value with @RepeatedTest annotation JUnit5我可以使用@RepeatedTest 注释JUnit5 获得变量值吗
【发布时间】:2020-01-27 10:46:42
【问题描述】:

我有一个测试用例,我以枚举的形式提供了我的测试数据。喜欢

enum TestTransactions {
    TestTransactions(Transaction T1, Transaction T2, String expectedOutput){}
}

在我的测试类中,我必须将其用作:

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 annotations repeat junit5


    【解决方案1】:

    如果我正确理解您的用例,您希望使用 @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();
            Assertions.assertEquals(currentTest.getExpectedOutput(), result.getBody());
        }
    }
    

    还有 JUnit 5 的附注:

    • @Test 方法应该是包私有的(没有可见性限定符),而不是 private
    • 使用Assertions 而不是Assert

    【讨论】:

      【解决方案2】:

      您遇到的是 Java 编译器的限制。除非 Java 语言规范将被更改,否则您无法做您想做的事情。

      您可以做的是向 Jupiter 提出功能请求以接受价值提供者,例如Class<? extends Supplier<Integer>> 类型。或者您可以使用 Jupiter 的动态测试功能对其进行模拟。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        • 2016-12-07
        相关资源
        最近更新 更多