java – 如何在下面的代码中模拟遗留对象?

我一直在使用mockito框架编写单元测试.

我在遗留代码下面有这个,如何在不重构的情况下在approvalAction方法中模拟RemoteService客户端对象?

public Map<String, String> approvalAction(long documentId, ActionCommandDTO request, FormData formData, byte[] prevData) {

    RemoteService client = getRemoteService();
    String urlString = String.format("formExtensions/%s?%s", formData.getId(), getAuthParam(formData.getRealm()));
    try {
        response = client.postEntity(urlString, String.class, approvalSvcRequestStr);
    } catch (Exception e) {
        // TODO: handle rollback properly for P2P
        handleApprovalActionFailed(documentId, request, formData, prevData);
    }

    return map;
}


private RemoteService getRemoteService() {

    RemoteServiceConfig remoteServiceConfig = (RemoteServiceConfig) this.serviceConfigRegistry.getServiceConfigs().get("approval");
    remoteServiceConfig.setClientID(clientId);
    remoteServiceConfig.setClientSecret(privateSecret);
    RemoteService remoteService = new RemoteService(remoteServiceConfig, authorizationHeaderServiceImpl);

    return remoteService;
}

最佳答案 为什么不通过构造函数使RemoteService可注入,还允许默认构造函数?

class YourClass{

    private final RemoteService client;

    public YourClass(RemoteService client){
        this.client = client;
    }

    public YourClass(){
        RemoteServiceConfig remoteServiceConfig = (RemoteServiceConfig) this.serviceConfigRegistry.getServiceConfigs().get("approval");
        remoteServiceConfig.setClientID(clientId);
        remoteServiceConfig.setClientSecret(privateSecret);
        client = new RemoteService(remoteServiceConfig, authorizationHeaderServiceImpl);
    }

    // all of your other methods inside the class

}

Of course you’d have to adapt your already existing constructors. but as you’ve not shown the whole class this is impossible for me.

这将在YourClass的整个生命周期内为您提供单个客户端实例.

现在,模拟RemoteService非常容易.只需使用模拟客户端实例化YourClass:

RemoteService mock = mock(RemoteService.class);
YourClass toTest = new YourClass(mock);
点赞