1

I am trying to mock a getStatusCode using mockito. but I am unable to mock getStatusCode using mockito

  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. errorMessage still depends on the url passed. But it should return null as response code is mocked as 200

Could someone tell where my I am doing wrong?

  • 2
    please post your actual code. the code you posted won't even compile. – Stultuske Sep 11 '19 at 10:18
  • This code not only doesn't compile, it's so far from compiling that there is no way to even guess what it's supposed to do. Post a [mcve]. – daniu Sep 11 '19 at 10:27

1 Answers1

0

It is because you haven't set your mock into the instance of 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. You can use FieldSetter in mockito to set that value before you call client1.getUserApi()

FieldSetter.setField(client1,
                     client1.getClass().getDeclaredField("listuserApi"), listuserApi1);
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62