当前位置: 首页 > 工具软件 > CF4Mock > 使用案例 >

单元测试当中,对于静态方法的Mock

法浩壤
2023-12-01

在springboot当中,调用

String agentId = CurrentAgentIdCatcher.get();

那么Mock的时候,需要引入PowerMock,但是PowerMock会导致jacoco进行覆盖的问题,从而需要设置
PowerMock从offLine设置为onLine。

下面的方法,不需要引入PowerMock:

将上面的方法,extract method

    /**
     * 获取agentId,方便单元测试的mock
     * @return
     */
    public String getAgentId() {
        String agentId = CurrentAgentIdCatcher.get();
        return agentId;
    }

在单元测试当中,使用spy

        VersionController spy = spy(versionController);
        Mockito.doReturn("d3a97cf4-023d-4fe9-a9c8-c3abd72e6eb6").when(spy).getAgentId();

当使用spy的时候,使用doReturn,则会使得不进行实际方法的调用,直接进行返回。

在使用deReturn的时候,注意

        // 正确调用 方法的调用要在when的后面,而不是里面
        PowerMockito.doReturn(false).when(stationCenterService).isDevMode();
        // 会出现异常信息
        PowerMockito.doReturn(false).when(stationCenterService.isDevMode());
 类似资料: