Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a class derived from a base class with lots of dependencies?

Im trying to unit test a class in some Java code that I've inherited.

Problem is that it derives from a class that is part of the company's application framwwork. Upon construction, the base class does all sorts of 'clever' stuff, initialising connections to all kinds of services that are needed at runtime.

But for unit testing purposes I dont need any of that. I just need to create an instance of the derived class and then I can excercise it. If any test specifically need part of the hierarchy I can mock them out.

So how do I break this dependency?

like image 386
PaulJWilliams Avatar asked Jun 19 '10 13:06

PaulJWilliams


1 Answers

Inheritance can be so brittle.

Is inheritance a requirement? All that "clever" stuff that the base class is doing (e.g., establishing connections) are things that a dependency injection engine would normally be providing.

Your class sounds like it would be better off from both a testing and a runtime standpoint if you find a way to not inherit and get its dependencies satisfied by a DI engine. Possible?

like image 120
duffymo Avatar answered Nov 15 '22 00:11

duffymo