How to create an abstract super test class in JUnit 4?

Consider the following specific scenario: someone has created many tests that fully test the functionality that a class implementing must adhere to Collection<E>. How then is it possible to use this test class (somehow) to test specific implementations Collection<E>?

Example:

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
}

How should I write test classes in such a way that the least duplication of code occurs?

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
}

In other words, is it possible to "extend CollectionTest", but its tests are executed on an instance ACollectionTestor BCollectionTest(or more)? Note that methods are still available if you use ACollection<E>like Collection<E>, for example.

+4
1

:

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<>();
}
+4

Source: https://habr.com/ru/post/1542681/


All Articles