簡體   English   中英

為什么 PowerMockito.whenNew 在我的代碼中沒有工作?

[英]Why PowerMockito.whenNew not woking in my code?

這是我的代碼,A class 中沒有模擬 AgentRest

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("");
    }
}

我嘗試了很多但仍然失敗,PowerMockito.whenNew 接縫不起作用,我已將所有 class 添加到 PrepareForTest

我發現問題是junit5不能使用powermock,解決方案鏈接: https://rieckpil.de/mock-java-constructors-and-their-object-creation-with-mockito/

這是我的新代碼:

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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM