I have legacy code I don\'t want to touch.
public class LegacyCode{
public LegacyCode() {
Service s = new ClassA();
s.getMessage();
}
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:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassA.class)
public class LegacyTester {
@Test
public void testService() {
// Inject your stub
PowerMock.createMock(ClassA.class);
Service stub = new MyServiceStub();
PowerMock.expectNew(ClassA.class).andReturn(stub);
PowerMock.replay(stub, ClassA.class);
// Implement test logic here
LegacyCode legacyCode = new LegacyCode();
// Implement Test steps
// Call verify if you want to make sure the ClassA constructor was called
PowerMock.verify(stub, ClassA.class)
}
}
This way you inject your stub when the call to ClassA
constructor happens, without changing the legacy code. Hope that's what you needed.