如何在 JUnit 4 中创建一种抽象的超级测试类?

ski*_*iwi 5 java junit unit-testing

考虑以下具体场景:有人创建了许多测试来完全测试类实现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
}
Run Code Online (Sandbox Code Playgroud)

那么我应该如何编写测试类,以便最少的代码重复发生?

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
}
Run Code Online (Sandbox Code Playgroud)

换句话说,是否可以“扩展 CollectionTest”,但是否可以在一个ACollectionTestBCollectionTest(或更多)实例上运行其测试?请注意,这些方法仍然可以访问,一旦你使用ACollection<E>Collection<E>例如。

JB *_*zet 5

在基类中:

protected Collection<Foo> collectionUnderTest;

@Test
public void shouldDoThis() {
    // uses collectionUnderTest
}

@Test
public void shouldDoThat() {
    // uses collectionUnderTest
}
Run Code Online (Sandbox Code Playgroud)

在子类中,特定于 ACollection 实现:

@Before
public void prepare() {
    this.collectionUnderTest = new ACollection<>();
}
Run Code Online (Sandbox Code Playgroud)

  • 我不明白为什么它们不能被使用。但这太模糊了。我的建议是:停止试图猜测或预测会发生什么,你能做什么和不能做什么。尝试这样做,你会看到会发生什么。 (2认同)