【问题标题】:How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests如何为多个参数化测试重用 JUnit Jupiter @MethodSource
【发布时间】:2019-12-28 22:39:57
【问题描述】:

假设我有以下代码:

class Testing {

    String[] text() {
        String[] text = { "A", "B" };
        return text;

    }

    @Nested
    class NestedTesting {

        @ParameterizedTest
        @MethodSource("text")
        void A(String text) {

            System.out.println(text);

        }

        @ParameterizedTest
        @MethodSource("text")
        void B(String text) {

            System.out.println(text);

        }
    }
}

当我运行它时,我得到:

No tests found with test runner 'JUnit 5'.

我怎样才能让它工作?我是 Java 初学者,所以我可能忘记了一些明显的事情

【问题讨论】:

    标签: java selenium junit5


    【解决方案1】:

    最简单的方法是通过其完全限定的方法名称引用static工厂方法——例如,@MethodSource("example.Testing#text()")

    为了进一步简化问题,您可以引入一个自定义的组合注释,它结合了@ParameterizedTest@MethodSource 的配置,如下所示:

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import org.junit.jupiter.params.ParameterizedTest;
    import org.junit.jupiter.params.provider.MethodSource;
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @ParameterizedTest
    @MethodSource("example.Testing#text()")
    public @interface ParameterizedTextTest {
    }
    

    然后您可以像这样重复使用它:

    package example;
    
    import org.junit.jupiter.api.Nested;
    
    class Testing {
    
        static String[] text() {
            return new String[] { "A", "B" };
        }
    
        @Nested
        class NestedTesting {
    
            @ParameterizedTextTest
            void testA(String text) {
                System.out.println(text);
            }
    
            @ParameterizedTextTest
            void testB(String text) {
                System.out.println(text);
            }
        }
    }
    

    测试愉快!

    【讨论】:

    • 我认为@MethodSourcevalue() == methodName() 和可选的className() 一起使用会很有意义。会更直观。
    猜你喜欢
    • 2017-05-23
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多