S T
S T

Reputation: 61

Writing junit tests to deal with inheritance hell

I'm looking to add some junit to our code base.

We have a set of classes that inherited from an abstract base class. The inheritance is several layers deep (Base-> A, B, C ->C1, C2, C3->C3-1, etc). Sometimes someone overrides a method of a class (Class A) which has several child classes. But because of that, we get bad results for those in call children classes of Class A.

So, I'm looking for solutions to be able to try to prevent this and create a testing framework to deal with this.

My initial though is that we would need to create a TestSuite that would need to check that the TestClass has at least 1 test case for every method in the Base class via reflections. This would make sure the person who added a overridden a method in a mid-level Class know that their change will affect child classes.

Also, I was talking to someone who said that there might be library already out there that does this.

I'm looking for thoughts and examples of how to write tests to handle this scenario. Refactoring is not an option in this case.

Upvotes: 1

Views: 612

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Sorry, but the proper answer to a bad design is not to "fix" it by coming up with "interesting" unit tests.

You fix a bad design by fixing the bad design.

In other words: the very first thing about OO to understand is LSP (Liskov substitution principle). In other words: when your developers change something in "the middle" of your inheritance tree, and that causes unexpected behavior in child classes further down, then you should rather invest in education and design sessions.

Beyond that, you don't need specific testing. When all public methods of your public classes are thoroughly tested, then you should quickly catch such kind of problems. But there is no way to determine pro grammatically that you have good tests for all classes. The fact that there are n test methods for some method X ... doesn't tell anything about the quality of any of the test methods. It doesn't help to know that you have "enough" tests ... but sorry, unfortunately, half of the tests isn't doing proper checking/verification; and thus they just keep passing all the time.

Long story short: you are looking at an XY problem here. Your Y problem is "our tests don't fail when we mess up code". But your X problem is: you created a bad design in the first place; and now you are searching for ways to work around that. And that will simply not work out in the long run.

Upvotes: 1

Related Questions