将外部定义的变量传递到@ParameterizedTest中的JUnit @ValueSource注解

qmb5sa22  于 2023-04-30  发布在  其他
关注(0)|答案(2)|浏览(97)

我有一个字符串数组,我想用于多个单元测试。为了消除代码的重复,并尽量减少将来需要对测试参数进行的更改,我尝试在JUnit测试类中定义一个变量,然后重用该变量作为每个@ValueSource注解的输入参数。这是可能的,还是我忽略了一个简单的错误?

private static final String[] myParameters = {"a", "b", "c"};

// This fails with the message that `myParameters` isn't a recognized symbol, probably because it's not a valid Element for @ValueSource
@ParameterizedTest
@ValueSource(myParameters)
public void myTest(String param) {
  // doesn't compile
}

// This fails with the message that "incompatible types: String[] cannot be converted to String"
@ParameterizedTest
@ValueSource(strings = myParameters)
public void myTest(String param) {
  // doesn't compile
}

// This works fine, but I would need to duplicate the values of `strings` for each test
@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
public void myTest(String param) {
  // works fine, but its duplicative in terms of the @ValueSource parameter
}

参考文献:

htrmnn0y

htrmnn0y1#

我建议你使用一个@MethodSource来 Package 你的常量:

private static final String[] myParameters = {"a", "b", "c"};

static List<String> myParameters() {
    return Arrays.asList(myParameters);
}

@ParameterizedTest
@MethodSource("myParameters")
public void myTestWithMethodSource(String param) {
    System.out.println(param);
}
lnlaulya

lnlaulya2#

我不确定你是否可以用@ValueSource实现这一点,但可以肯定的是,用@MethodSourceDynamicTests可以做到这一点:

@ParameterizedTest
@MethodSource("myParameters")
public void myTest(String param) {
    System.out.println(param);

}

Stream<String> myParameters() {
    return Stream.of("a", "b", "c");
}

或者,这就是动态测试的方法。这是junit5的一个很酷的特性,它允许你动态地创建单元测试:

static Stream<String> myParameters() {
    return Stream.of("a", "b", "c");
}

@TestFactory
Stream<DynamicTest> myTests() {
    return myParameters()
        .map(p -> DynamicTest.dynamicTest(
             "testing for: " + p, 
              () -> myTest(p)
        ));
}

void myTest(String param) {
    System.out.println(param);
    assertEquals(1, param.length());
}

如果你觉得这很有趣,在这里阅读更多:https://medium.com/javarevisited/streamline-your-testing-workflow-with-junit-5-dynamic-tests-66787740f39c?sk=b10eacd4e6f6b85c51f194b240555895

相关问题