使用mockito为一个宁静的客户提供Junit测试用例

时间:2015-07-21 20:24:28

标签: java rest testing junit mockito

我不知道如何编写测试用例,当我看到在线教程时,我理解如何编写一个带有成功和失败场景的简单方法。现在我有一个http get的方法,它调用一个restful API并返回一个json响应。我有6个参数要包含在url中并获得json响应。现在,我到目前为止的理解是成功的情况在这里我应该硬编码那些输入参数并测试我是否正在获得json并且失败没有得到json响应。这是正确的还是我必须做其他事情?

我的意思是我有一个类似

的代码
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;

}

2 个答案:

答案 0 :(得分:1)

也许你应该看看REST-assured,这是一个REST API测试框架。

好消息是,它更容易阅读,支持JSON和XML,并允许您测试HTTP代码或响应中的特定值等内容。

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

您可以使用param方法添加参数:

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

如果您需要身份验证,就像在代码中一样,您可以使用以下内容:

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

希望这有助于您的测试。

答案 1 :(得分:0)

看起来你需要模仿该方法的主要因素是HTtpClient。那么你如何创建一个获取客户端的方法,然后模拟该方法,以便它返回一个模拟HttpClient。

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

然后在你的方法中你会做:

HttpClient httpclient = getHttpClient();

然后在您的单元测试代码中,您将模拟getHttpClient方法,如此...

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

类似的东西。