Alice Walker
Alice Walker

Reputation: 21

Junit test case for a restful client using mockito

I have no idea before how to write the test cases, when i saw online tutorials i understand how to write it for a simple method with success and failure scenario. Now i have a method for http get which calls a restful API and returns a json response. I have like 6 parameters to include in the url and get a json response back. Now, my understanding so far is for success scenario here i should just hard code those input parameters and test if i am getting json back and for failure not getting json response back. Is this correct or do i have to do something else?

i mean i have a code something like

public List getStoreLocations(StoreData storeData) {
  List storeList = null;

  try {
    HttpClient httpclient = HttpClientBuilder.create().build();
    StringBuilder urlStrngBuildr = new StringBuilder(
            https://<hostname>/xyz/abc);
    Utility.addParameterToUrl(urlStrngBuildr,
            Utility.APP_NAME,
            Constants.APP_VALUE);
    Utility.addParameterToUrl(urlStrngBuildr,
            Constants.VERSION_PARAM_NAME,
            Constants.VERSION_PARAM_VALUE);
    if (storeData.getCity() != null && storeData.getState() != null) {
        StringBuilder addressParamValue = new StringBuilder(
                storeData.getCity());
        addressParamValue.append(Constants.COMMA);
        addressParamValue.append(storeData.getState());
        Utility.addParameterToUrl(urlStrngBuildr,
                Constants.ADDRESS_PARAM_NAME,
                addressParamValue.toString());
    } else if (storeData.getZip() != null) {
        Utility.addParameterToUrl(urlStrngBuildr,
                Constants.ZIP_PARAM_NAME, storeData.getZip());
    }

    Utility.addParameterToUrl(urlStrngBuildr,
            Constants.PRODUCT_PARAM_NAME,
            storeData.getProduct());
    Utility.addParameterToUrl(urlStrngBuildr,
            Constants.COUNTRY_PARAM_NAME,
            storeData.getCountry());
    Utility.addParameterToUrl(urlStrngBuildr,
            Constants.DISTANCE_PARAM_NAME,
            storeData.getDistance());
    Utility.addParameterToUrl(urlStrngBuildr,
            Constants.SIZE_PARAM_NAME, storeData.getSize());

    HttpGet getRequest = new HttpGet(new java.net.URI(
            urlStrngBuildr.toString()));

    getRequest.addHeader(BasicScheme.authenticate(
            new UsernamePasswordCredentials(username,password),
        Constants.ENCODING_TYPE, false));

    JSONResponseHandler responseHandler = new JSONResponseHandler();
    String json = httpclient.execute(getRequest, responseHandler)
            .toString();

    Gson gson = new Gson();

    StoreResponse response = gson.fromJson(json,
            StoreResponse.class);

    StoreDetails[] strDetails = response.getResult();

    storeDetailsList = Arrays.asList(strDetails);

  } catch (Exception exeption) {
    exeption.printStackTrace();
  }

  return storeList;

}

Upvotes: 2

Views: 7264

Answers (2)

Jose Martinez
Jose Martinez

Reputation: 11992

It looks like the main thign you need to mock on that method is the HTtpClient. So how about you create a method for getting the client, then mock that method so that it returns a mock HttpClient.

public HttpClient getHttpClient(){
    return HttpClientBuilder.create().build();
}

Then in your method you will do:

HttpClient httpclient = getHttpClient();

Then in your unit test code you will mock the getHttpClient method like so..

HttpClient  mockClient = mock(HttpClient.class);  
MyClassBeingTested instance = spy(new MyClassBeingTested ());  
when(instance .getHttpClient()).thenReturn(mockClient);  
when(mockClient.execute(any(HttpGet.class),any(JSONResponseHandler.class)).thenReturn(testJsonString);  
List actual = instance.getStoreLocations(storeData);  

Something like that.

Upvotes: 0

kamwo
kamwo

Reputation: 2000

Maybe you should take a look at REST-assured, which is a REST API testing framework.

The nice thing is, that it is much easier to read, supports JSON and XML and allows you to test things like HTTP-Codes or specific values from the response.

get("/lotto")
   .then()
      .assertThat().body("lotto.lottoId", equalTo(5));

You could add your parameters with the param method:

given()
    .param("key1", "value1")
    .param("key2", "value2")
when().
   aso...

If you need authentication, like in your code, you can just use something like the following:

given()
  .auth()
     .basic(username,password)
  .when()
     .get("/secured")
  .then()
     .statusCode(200);`

Hope this helps with your testing.

Upvotes: 1

Related Questions