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.
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.
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.
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.
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<>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With