JUnit5:测试多个类而无需重复代码 [英] JUnit5: Test multiple classes without repeating code
问题描述
我已经用Java构建了自己的堆栈实现,如下所示:
I have built my own implementation of a stack in Java, which looks something like this:
有一个堆栈"接口,提供基本功能(弹出,推入,偷看等).然后,我有2个具体的类,一个是借助数组的类,另一个是具有链表的类(在这种情况下,这并不重要).
There is the interface "Stack" which provides the basic functions (pop, push, peek etc.). And then I have 2 concrete classes, one with the help of arrays and the one with a linked list (how is not important in this case).
现在我的问题是:我想用JUnit5进行测试,因为您无法实例化接口,所以我必须对数组的类和链接列表的类分别测试每个功能,因此代码太长了.有没有一种方法可以测试该接口的所有功能或类似功能?因为如果现在添加了第三个实现,那么我将不得不再次重写所有实现.
Now my question: I want to test this with JUnit5 and because you can't instantiate an interface, I have to test each function once for the class with the arrays and once for the class with the linked list, so the code is unnecessarily long. Is there a way that I can test all functions for the interface or something similar? Because if now a third implementation was added, I'd have to rewrite it all again.
我已经尝试过'ParameterizedTests',但是没有取得任何进展.
I have already tried 'ParameterizedTests', but I have not made any progress.
我很乐意提供帮助!
推荐答案
我不知道您遇到的@ParameterizedTest
问题是什么,但是如您所要求的,这是一个非常通用的测试示例,可能对您的测试有用:
I do not know what problem with @ParameterizedTest
you are facing, but as you requested this is a very generic test example which could be useful for your test:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
...
public static Stream<Arguments> provideStacks() {
return Stream.of(
Arguments.of(new ArrayStack()),
Arguments.of(new LinkedStack())
);
}
@ParameterizedTest
@MethodSource("provideStacks")
public void test(Stack stack) {
stack.push(1);
assertEquals(1, stack.pop());
}
public interface Stack {
void push(int i);
int pop();
}
public static final class ArrayStack implements Stack {
@Override
public void push(int i) {
}
@Override
public int pop() {
return 1;
}
}
public static final class LinkedStack implements Stack {
@Override
public void push(int i) {
}
@Override
public int pop() {
return 1;
}
}
这篇关于JUnit5:测试多个类而无需重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!