简体   繁体   English

使用嘲笑在另一个方法中模拟一个方法。 基本上想模拟methodA来测试statusMethod

[英]Mocking a method inside another method using mockito. Basically want to mock methodA for testing statusMethod

I am trying to mock a getStatusCode using mockito. 我正在尝试使用Mockito模拟一个getStatusCode。 but I am unable to mock getStatusCode using 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;
}

I have tried this approach: 我已经尝试过这种方法:

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

But 200 is not returned which means mocking line is not executed. 但是不会返回200,这意味着不执行模拟行。 errorMessage still depends on the url passed. errorMessage仍然取决于传递的url。 But it should return null as response code is mocked as 200 但它应返回null,因为响应代码被模拟为200

Could someone tell where my I am doing wrong? 有人可以告诉我我在哪里做错了吗?

It is because you haven't set your mock into the instance of client1 . 这是因为您尚未将模拟程序设置为client1的实例。 As this is more like design problem of your class Client , you have to use reflection to set the mock to that private variable. 因为这更像是类Client设计问题,所以必须使用反射将模拟设置为该私有变量。 You can use FieldSetter in mockito to set that value before you call client1.getUserApi() 您可以在调用client1.getUserApi()之前在嘲笑中使用FieldSetter设置该值。

FieldSetter.setField(client1,
                     client1.getClass().getDeclaredField("listuserApi"), listuserApi1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM