我有一个字符串数组,我想用于多个单元测试。为了消除代码的重复,并尽量减少将来需要对测试参数进行的更改,我尝试在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
}
参考文献:
- Annotation Type ValueSource
- JUnit GitHub
2条答案
按热度按时间htrmnn0y1#
我建议你使用一个
@MethodSource
来 Package 你的常量:lnlaulya2#
我不确定你是否可以用
@ValueSource
实现这一点,但可以肯定的是,用@MethodSource
和DynamicTests
可以做到这一点:或者,这就是动态测试的方法。这是junit5的一个很酷的特性,它允许你动态地创建单元测试:
如果你觉得这很有趣,在这里阅读更多:https://medium.com/javarevisited/streamline-your-testing-workflow-with-junit-5-dynamic-tests-66787740f39c?sk=b10eacd4e6f6b85c51f194b240555895