考虑以下具体场景:有人创建了很多测试来全面测试类实现 Collection<E>
的功能。必须坚持。那么如何使用该测试类(以某种方式)来测试 Collection<E>
的具体实现呢? ?
举例:
public class CollectionTest {
//lots of tests here
}
public class ACollection<E> implements Collection<E> {
//implementation and custom methods
}
public class BCollection<E> implements Collection<E> {
//implementation and other custom methods
}
然后我应该如何编写测试类以使代码重复发生最少?
public class ACollectionTest {
//tests for Collection<E>, preferably not duplicated
//tests for custom methods
}
public class BCollectionTest {
//tests for Collection<E>, preferably not duplicated
//tests for other custom methods
}
换句话说,是否可以“扩展 CollectionTest”,但让它的测试在 ACollectionTest
的实例上运行?或 BCollectionTest
(或者更多)?请注意,一旦您使用 ACollection<E>
,这些方法仍然可以访问作为Collection<E>
例如。
最佳答案
在基类中:
protected Collection<Foo> collectionUnderTest;
@Test
public void shouldDoThis() {
// uses collectionUnderTest
}
@Test
public void shouldDoThat() {
// uses collectionUnderTest
}
在子类中,具体到ACollection的实现:
@Before
public void prepare() {
this.collectionUnderTest = new ACollection<>();
}
关于java - 如何在 JUnit 4 中创建一种抽象的 super 测试类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960060/