I have legacy code I don't want to touch.
public class LegacyCode{
public LegacyCode() {
Service s = new ClassA();
s.getMessage();
}
}
Where ClassA
provides a CORBA service call.
public class ClassA implements Service{
@Override
public String getMessage() {
// Make CORBA service call...
return "Class A";
}
}
And the interface Service
looks like;
public interface Service {
String getMessage();
}
For test purposes, I want to replace the implementation of Service
(in LegacyCode
implemented by ClassA
) with a stub.
public class ClassB implements Service {
@Override
public String getMessage() {
return "Stub Class B";
}
}
So far so good. But is it possible without any modifications at the shown legacy code to load ClassB
instead of ClassA
at the instantiation of ClassA
?
// In my test workbench
new LegacyCode(); // "Stub Class B"
I've tried to write a custom classloader and load it at application start by java vm arguments but only the first class (here LegacyCode
) was loaded by that loader.
Thanks in advance
Using
PowerMock
you can create a mock (or stub) for a constructor code. The answer is taken from this link. I'll try to convert it to match exactly to your use case:This way you inject your stub when the call to
ClassA
constructor happens, without changing the legacy code. Hope that's what you needed.The easier thing to do is to just create a
ClassA
in your test code. Declare it in the same package originally found in the actual code and use the same method names. Just make the method do nothing.For example, if your project structure looks like this:
Create an alternative
ClassA
under/src/test/java/com/company/code/
:Now your project structure will look like this:
When your unit tests execute, the
ClassA
from yourtest
folder will be loaded. This is way simpler than using a mock framework especially if your old code is messy, not dependency-injection-friendly and the actualClassA
is used everywhere.Just keep in mind that this sort of strategy can make your test code a bit more obscure, and you can't test the actual implementation of
ClassA
itself, nor easily provide alternative implementations for different test scenarios.One way would be with AspectJ. I agree with Hovercraft, this is a good case for dependency injection but if you can't change the source code, AspectJ might be your tool of choice.
This explains the AspectJ case better than I can: Can AspectJ replace "new X" with "new SubclassOfX" in third-party library code?