1

I have an abstract class that has good test coverage. I want to make sure that any extensions of that class also pass the tests of the abstract class. Is there any way to ensure this with code using JUnit?

Lumpy
  • 3,632
  • 4
  • 34
  • 58
  • Would it be possible to add an example to your question? – Chetan Kinger May 29 '15 at 14:36
  • I can under stand your pain, but there is freedom given to sub-classes creators not other way. I don't know think there is a way. – bobs_007 May 29 '15 at 14:43
  • for an example: if classB overrides a method of classA I want to make sure testClassAMethod still passes for classB or force classB to also override testClassAMethod – Lumpy May 29 '15 at 14:57
  • i think only way to do is manually code test for all subclasses of base class, but thanks to polymorphism u need only one test method for them all. – itwasntme May 29 '15 at 15:22

3 Answers3

1

All the method that didn't changed in you sub-classes are checked in the test of your abstract class. The method that was not changed don't need to be tested again under the scope of the extending classes.

If some method was override it will be a vary bad decision to apply the same tests on them as they might have different business logic. Hence if someone inherit your class he should write his own tests for the methods that he had overridden.

This is all the point of inheritance to change or add logic business logic.

Moshe Tsabari
  • 362
  • 3
  • 17
  • The issue I'm trying to solve is that the person extending the class, might not know all the ways it can break. If they override the class and see that a test fails, they can either override the test, or fix the method to not fail the test. Otherwise, they don't even know that their code is breaking. – Lumpy Jun 01 '15 at 15:59
1

So I thought about some workaround I dont know if you will like it but lets try.

My solution is to make test that find all implementation of your Abstract class Instantiate all the concert classes And then it will run the same tests on all of them.

You will need the following API for getting all subclass by reflection

 <dependency>
         <groupId>org.reflections</groupId>
         <artifactId>reflections</artifactId>
         <version>0.9.9-RC1</version>
 </dependency>

and then use it like this

Reflections reflections = new Reflections("packageName");
Set<Class<? extends YourClass>> classes = reflections.getSubTypesOf(YourClass.class);

And then Instantiate and run

To run each test with different implemention you will need @RunWith(Parameterized.class)

this is a link on how to do Parameterized test in Junit

Easy way of running the same junit test over and over?

Community
  • 1
  • 1
Moshe Tsabari
  • 362
  • 3
  • 17
0

I don't think there's a simple way to do it automatically.

See this question on trying to get all subclasses of a given class for more details on why.

Community
  • 1
  • 1
Phil Anderson
  • 3,146
  • 13
  • 24