我正在尝试使用mockito模拟getStatusCode。 但我无法使用mockito模拟getStatusCode
public class Client {
private ApiClient adminApiClient;
private UserApi listuserApi;
public Client(String Url) {
this.adminApiClient = new ApiClient().setBasePath(Url + "/admin/");
this.listuserApi = new UserApi(this.adminApiClient);
}
public String getUser() {
String errorMessage = null;
try {
ApiResponse<User> response =
listuserApi.listVpcUsersWithHttpInfo("string");
if (response.getStatusCode() != 200) {
errorMessage = "Agent returned response code " +
response.getStatusCode();
}
} catch (Exception ex) {
errorMessage = "error"
}
return errorMessage;
}
我尝试过这种方法:
url = "www.google.com";
Client client = new Client(url);
Client client1 = Mockito.spy(client);
ApiClient adminApiClient = new ApiClient().setBasePath(url + "/zsaadmin/");
UserApi listuserApi = new UserApi(adminApiClient);
UserApi listuserApi1 = Mockito.spy(listuserApi);
ApiResponse<User> response = Mockito.mock(ApiResponse.class);
Mockito.when(listuserApi1.listVpcUsersWithHttpInfo("string")).thenReturn(response);
//Mocking line
Mockito.when(response.getStatusCode()).thenReturn(200);
String errorMessage = client1.getUserApi();
//Since response.getStatusCode is 200, the errorMeassage should be null
assertEquals(null,errorMessage);
但是没有返回 200,这意味着不会执行模拟行。 错误消息仍然取决于传递的 url。但它应该返回 null,因为响应代码被模拟为 200
有人能说出我哪里做错了吗?
这是因为您尚未将模拟设置为client1
的实例。由于这更像是类Client
的设计问题,您必须使用反射将模拟设置为该私有变量。您可以在 mockito 中使用 FieldSetter 在调用client1.getUserApi()
之前设置该值
FieldSetter.setField(client1,
client1.getClass().getDeclaredField("listuserApi"), listuserApi1);