如何解决JUnit5 - 如何将输入集合传递给 ParameterizedTest
我正在尝试将 ParameterizedTest
从 JUnit4 转换为 junit5(遗憾的是我不是特别擅长测试)。
在 JUnit4 中,我有以下类:
@RunWith(Parameterized.class)
public class AssertionTestCase {
private final TestInput testInput;
public AssertionTestCase(TestInput testInput) {
this.testInput = testInput;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return AssertionTestCaseDataProvider.createDataCase();
}
@Test(timeout = 15 * 60 * 1000L)
public void testDailyAssertion() {
LOG.info("Testing input {}/{}",testInput.getTestCase(),testInput.getTestName());
//assert stuffs
}
}
在 AssertionTestCaseDataProvider
类中,我有一个生成 Object[]
集合的简单方法:
class AssertionTestCaseDataProvider {
static Collection<Object[]> createDataCase() {
final List<TestInput> testInputs = new ArrayList<>();
//create and populate testInputs
return testInputs.stream()
.map(testInput -> new Object[]{testInput})
.collect(Collectors.toList());
}
}
我一直在尝试使用 junit5 翻译它并获得了这个:
class AssertionTestCase {
private final TestInput testInput;
public AssertionTestCase(TestInput testInput) {
this.testInput = testInput;
}
public static Collection<Object[]> data() {
return AssertionTestCaseDataProvider.createDataCase();
}
@ParameterizedTest
@MethodSource("data")
void testDailyAssertion() {
LOG.info("Testing input {}/{}",testInput.getTestName());
// assert stuffs
}
}
我没有对 AssertionTestCaseDataProvider
类应用任何更改。
不过,我收到以下错误:
No ParameterResolver registered for parameter [com.xxx.xx.xxx.xxx.testinput.TestInput arg0] in constructor [public `com.xxx.xxx.xxx.xxx.xxx.AssertionTestCase(com.xxx.xxx.xxx.xxx.testinput.TestInput)]. org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [com.xxx.xx.xxx.xxx.testinput.TestInput arg0] in constructor [public com.xxx.xxx.xxx.xxx.xxx.AssertionTestCase(com.xxx.xxx.xxx.xxx.testinput.TestInput)].`
我知道在初始化测试的输入集合时我可能没有正确应用 junit5。我是否缺少一些注释?
我还尝试使用 @ArgumentSource
代替 @MethodSource
并为 Argument
实现 AssertionTestCaseDataProvider
,但结果相同。
解决方法
它在 Junit5 中的工作方式有点不同。
测试方法应该有参数,提供者方法应该返回一个 Stream
。
static Stream<Arguments> data(){
return Stream.of(
Arguments.of("a",1),Arguments.of("d",2)
);
}
@ParameterizedTest
@MethodSource("data")
void testDailyAssertion(String a,int b) {
Assertions.assertAll(
() -> Assertions.assertEquals("a",a),() -> Assertions.assertEquals(1,b)
);
}
在你的情况下,你可以只返回一个 Stream
static Stream<TestInput> createDataCase() {
final List<TestInput> testInputs = new ArrayList<>();
//create and populate testInputs
return testInputs.stream();
}
然后在您的测试方法中:
@ParameterizedTest
@MethodSource("createDataCase")
void testDailyAssertion(TestInput testInput) {
{your assertions}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。