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?
So you have a base class and an extended class. See if you can refactor the extended class to no longer extend the base class, but use it instead. So where you first called
parent::fooBar(), you now callthis.baseInstance.fooBar(). This way, you can inject another baseInstance for test purposes.If you really need to extend the base class to override something, extract the functionality to a third class and make the extended class a proxy. The extended class does nothing else than call methods on the third class. E.g.
This way, you can test the real implementation, without instantiating the base class.