2017-05-31 76 views
0

我很抱歉問這個問題,因爲我非常肯定這已經被問到了。但通過在這裏搜索或谷歌我總是登陸REST服務與傳入請求進行測試的網站。在春季測試一個傳出的HTTP請求

在我的情況下,我有一種方法,發送請求到服務器。我想測試這個請求是否正確。我使用java和spring引導。每次我測試時,請求都會發送到服務器。我可以攔截嗎?

public void buy(double price) { 
     final String timestamp = String.valueOf(System.currentTimeMillis()); 
     final String amount = String.valueOf(observer.requestedAmount); 
     final String ressouce = GetValuesTypes.getRessource("user").get(observer.getRelatedUser); 

     String queryArgs = "wwww.doSomething.com/" + ressouce; 
     String hmac512 = HMAC512.hmac512Digest(queryArgs); 

     CloseableHttpClient httpClient = HttpClients.createDefault(); 
     HttpPost post = new HttpPost(GetValuesTypes.getURL()); 
     post.addHeader("Key", GetValuesTypes.getKey()); 
     post.addHeader("Sign", hmac512); 
     try { 
      post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8"))); 
     } catch (UnsupportedEncodingException e) { 
      System.out.println("Exception in run"); 
     } 
     List<NameValuePair> params = new ArrayList<>(); 

     params.add(new BasicNameValuePair("command", "order")); 
     params.add(new BasicNameValuePair("ressource", ressource)); 
     params.add(new BasicNameValuePair("rate", String.valueOf(rate))); 
     params.add(new BasicNameValuePair("amount", amount)); 
     params.add(new BasicNameValuePair("timestamp", timestamp)); 
     try { 
      post.setEntity(new UrlEncodedFormEntity(params)); 
      CloseableHttpResponse response = httpClient.execute(post); 
      HttpEntity entity = response.getEntity(); 
      Scanner in = new Scanner(entity.getContent()); 
      String orderNumber = ""; 
      while (in.hasNext()) { 
       orderNumber = in.nextLine(); 
      } 
      String[] findOrderNumber = orderNumber.split("."); 
      long lastOrderNumber = -1; 
      try { 
       lastOrderNumber = Long.valueOf(findOrderNumber[3]); 
      } catch (NumberFormatException exception) { 
       System.out.println("NumberFormatException"); 
      } finally { 
       if (lastOrderNumber != -1) { 
        observer.setOrderNumber(lastOrderNumber); 
       } 
      } 
      in.close(); 
      EntityUtils.consume(entity); 
      httpClient.close(); 
     } catch (IOException e) { 
      System.out.println("Exception occured during process"); 
     } 
    } 

非常感謝您的幫助。

+0

你有沒有測試你的代碼?如同,你在說什麼? – pandaadb

回答

0

這是所有嘗試爲其代碼編寫測試的人都面臨的一個典型問題(這也意味着網絡上有很多關於如何執行的文章)。

在這種特殊情況下,我看到了兩種方式:

  • ,如果你想要寫一個單元測試:而不是創建HttpClient的,你應該讓配置,能夠通過模擬在替代它單元測試。您可以將其保存爲類成員,或將其作爲第二個參數提供給buy()方法。之後,在單元測試中,您需要提供假版本的HttpClient(模擬),允許您檢查其參數以確保它們與預期相同。

  • 如果你想寫一個集成測試:你需要運行一個假的服務,其行爲像一個真實的服務器,但也允許檢查收到的請求。在集成測試中,您需要配置HttpClient連接到此假服務器,然後檢查服務器是否接收到來自客戶端的請求。

如何實現這一點,取決於您和您熟悉的技術。

+0

謝謝你的回答Slava。這在目前聽起來非常困難。我知道如何模擬可以測試接口的類,但是替代HttpClient對我來說是新手。你能推薦任何教程,或者你有代碼片斷嗎? – AnnaKlein

+0

HttpClient已經是一個接口:https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/HttpClient.html所以它不應該很難。 –