Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sort of abstract super test class in JUnit 4?

Consider the following concrete scenario: Someone has created a lot of tests that fully test the functionality to which a class implementing Collection<E> must adhere. How is it then possibly to use that test class (in some way) to test concrete implementations of Collection<E>?

By 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 then write the test classes such that least code duplication 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 have its tests run on an instance of ACollectionTest or BCollectionTest (or more)? Note that the methods are still accessible once you use ACollection<E> as Collection<E> for example.

like image 300
skiwi Avatar asked May 30 '14 17:05

skiwi


People also ask

Can we write Junits for abstract class?

With JUnit, you can write a test class for any source class in your Java project. Even abstract classes, which, as you know, can't be instantiated, but may have constructors for the benefit of “concrete” subclasses.

Do we need to write test cases for abstract class?

Also, writing unit tests for abstract class methods is as important as for normal classes and methods. We can test each of them using different techniques or different test support libraries available.

What is @after in JUnit?

org.junit If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.


1 Answers

In the base class:

protected Collection<Foo> collectionUnderTest;

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

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

In the subclass, specific to the ACollection implementation:

@Before
public void prepare() {
    this.collectionUnderTest = new ACollection<>();
}
like image 114
JB Nizet Avatar answered Oct 20 '22 06:10

JB Nizet