Replace implementation of instantiated class without touching the code (java)

后端 未结 3 941
谎友^
谎友^ 2021-01-13 18:52

I have legacy code I don\'t want to touch.

public class LegacyCode{
    public LegacyCode() {
        Service s = new ClassA();
        s.getMessage();
    }         


        
3条回答
  •  太阳男子
    2021-01-13 18:54

    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.

提交回复
热议问题