gpt4 book ai didi

java - 测试实现相同接口(interface)的类的最佳方法

转载 作者:行者123 更新时间:2023-12-02 05:29:49 24 4
gpt4 key购买 nike

例如,我有几个类实现 List<T>界面。如何测试它们——它们是否正确实现了方法?

现在我只看到一种方法:

public class MyListImplementationsTest {
private Collection<List<Integer>> listImplementations;

@BeforeClass
public static void setUp() throws Exception {
listImplementations = Arrays.asList(
new QuickList<Integer>(), new EfficientMemoryList<Integer>()
);
}

@Test
public void testIsEmptyAfterCreationEmptyList() {
// Use forEachList(handler) in order to not iterate
// the lists manually every time.
// May be there is no need to do so,
// because using <<for (item : items)>> instead of
// iterating using index prevents from OutOfBounds errors
forEachList(new OnEachListHandler<Integer>() {
@Override
public void onEach(List<Integer> list) {
assertTrue(list.isEmpty());
}
});
}

private <T> void forEachList(OnEachListHandler<T> handler) {
for (List<T> each : listImplementations) {
handler.onEach(each);
}
}

private static interface OnEachListHandler<T> {
void onEach(List<T> each);
}
}

但在我看来,在每个测试中迭代列表很复杂。

是否有更优雅的方法来测试 JUnit4 中实现相同接口(interface)的类?

最佳答案

您可以创建一个基本测试,可以测试 List<T> 类型的任何内容。加上一个创建这样一个列表的抽象方法。

然后对每个列表类型实现一个测试,以扩展基本测试。 JUnit 将从基类以及您在扩展中定义的任何测试用例运行。

abstract class AbstractListTest<T> {
protected abstract List<T> createList();

@Test
public void testIsEmpty() {
List<T> list = createList();
assertTrue(list.isEmpty());
}

...more tests...
}

class QuickListTest extends AbstractListTest<QuickList> {
protected QuickList createList() {
return new QuickList();
}
}

JUnit 不会运行抽象基类,但它将查看继承的测试并运行所有测试。您还可以将新测试添加到 QuickListTest或覆盖基类中的。

基本上,JUnit会走类,找到所有public @Test整个继承树中的方法并运行它们。

关于java - 测试实现相同接口(interface)的类的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25669917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com