java - 如何在 JUnit 4 中创建一种抽象的 super 测试类?

标签 java unit-testing junit

考虑以下具体场景:有人创建了很多测试来全面测试类实现 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/

相关文章:

java - 在 Linux 浏览器(或 Linux 命令行)中为 Java 证书信任库导出 SSL 证书

java - JXMapKit离线

c# - 使用 Azure DocDB 创建用于单元测试的 ResourceResponse 对象

javascript - QUnit 模拟自动完成

java - 如何验证方法内部正在启动的方法?

java - 我需要在单元测试中模拟 RabbitMQ

java - 如何为 csv java 记录器文件设置 header 。使用记录器 java.util.logging.Logger

java - 如何将循环值设置为文本字段?

android - Mockito 模拟在 Lollipop 或更高版本中运行实际的 Android 代码

java - 使用 Mockito 的 doThrow 方法时不会抛出异常