gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:31:12 30 4
gpt4 key购买 nike

我一直在使用 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 可以通过构造函数注入(inject),同时还允许默认构造函数?

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

关于java - 如何在下面的代码中模拟遗留对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54107618/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com