Search code examples
javamockitopowermock

Why PowerMockito.whenNew not woking in my code?


here is my code, AgentRest is not mocked in A class

class A {
    public void t() throws IOException {
        AgentRest agentRest = new AgentRest("127.0.0.1", 8888);
        HttpResponse<TaskStatusResponse> a = agentRest.dataBackup(null); // not mock
    }
}

@Slf4j
@PrepareForTest({A.class, SftpClientTest.class,AgentRest.class })
@RunWith(PowerMockRunner.class)
class SftpClientTest {
    
    @Test
    void getHome() throws Exception {
        HttpResponse<TaskStatusResponse> httpResponse =
                HttpResponse.<TaskStatusResponse>builder().code(0).body(TaskStatusResponse.builder().status("").build()).build();

        AgentRest agentRest = PowerMockito.mock(AgentRest.class);
        PowerMockito.whenNew(AgentRest.class).withAnyArguments().thenReturn(agentRest);
        PowerMockito.when(agentRest.dataBackup(ArgumentMatchers.any())).thenReturn(httpResponse);

        new A().t();
        
        log.info("");
    }
}

i have try a lot but still failed, PowerMockito.whenNew seams not working, and i have added all class to PrepareForTest


Solution

  • I have found the probelm is junit5 is not working with powermock, solution link: https://rieckpil.de/mock-java-constructors-and-their-object-creation-with-mockito/

    here is my new code:

    class A {
        public void t() throws IOException {
            AgentRest agentRest = new AgentRest("127.0.0.1", 8888);
            HttpResponse<TaskStatusResponse> a = agentRest.dataBackup(null);
        }
    }
    
    @Slf4j
    class SftpClientTest {
    
        @Test
        void getHome() throws Exception {
            try (MockedConstruction<AgentRest> mocked = mockConstruction(AgentRest.class)) {
                HttpResponse<TaskStatusResponse> httpResponse =
                        HttpResponse.<TaskStatusResponse>builder().code(0).body(TaskStatusResponse.builder().status("").build()).build();
    
                // every object creation is returning a mock from now on
                AgentRest agentRest = new AgentRest("sa", 22);
                when(agentRest.dataBackup(ArgumentMatchers.any())).thenReturn(httpResponse);
                new A().t();
            }
        }
    }