【问题标题】:Junit test case for a restful client using mockito使用 mockito 的安静客户端的 Junit 测试用例
【发布时间】:2015-07-21 20:24:27
【问题描述】:

我之前不知道如何编写测试用例,当我看到在线教程时,我了解如何编写一个简单的方法,其中包含成功和失败的场景。现在我有一个 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;

}

【问题讨论】:

    标签: java rest testing junit mockito


    【解决方案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);`
    

    希望这对您的测试有所帮助。

    【讨论】:

      【解决方案2】:

      看起来您需要在该方法上模拟的主要思想是 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);  
      

      类似的东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-13
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        • 1970-01-01
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多