2016-07-26 33 views
1

我正在使用Rest Assured Framework進行API測試(使用Java)。 在第(1)行,由於期望的JSON響應和實際的JSON響應不匹配,我期待錯誤 但是相反,我的代碼正在成功執行。 有人可以告訴我,如果我在下面的代碼中做錯了什麼?Rest Assured Framework完整的JSON響應匹配

 public void test123() { 
      try { 
       //Read the Curl Request Input file 
       String json = input.readFromTextFile(
         System.getProperty("user.dir") + "\\src\\test\\resources\\inputFile\\CurlDataFile.txt"); 
       json = json.replaceAll(" ", "");    
       RestAssured.baseURI = "My URL"; 
       given(). 
        contentType("application/json"). 
        body(json). 
       when(). 
        post(""). 
       then(). 
assertThat().body(matchesJsonSchemaInClasspath("testCurlOuput1.json")); (1) 
      } catch (IOException e) { 
       e.printStackTrace(); 
      }catch(JsonSchemaValidationException e){ 
       e.printStackTrace(); 
      } 
     } 

回答

0

最後,我選擇了不同的庫,即jayway.restassured庫,然後JSON斷言庫(org.skyscreamer.jsonassert.JSONAssert),這將comapre實際和預期的響應。

public void test123() {   
String postData = input.readFromTextFile(System.getProperty("user.dir") + "\\src\\test\\resources\\inputFile\\CurlDataFile.txt"); 
     RestAssured.baseURI = "MY URL"; 
Response r = (Response)given().contentType("application/json").body(postData).when().post(""); 
      String responseBody = r.getBody().asString();   
      String curlResponse = //I am providing expected Curl response here   
     //JSON Assertion for matching Expected and Actual response 
      JSONAssert.assertEquals(curlResponse, responseBody, false); 
     } 

而且有時我們可能希望避免特定領域的JSON比較喜歡的一些ID字段動態生成,我們可以不使用JSON比較

0

您正在捕捉所有異常。當你的assertThat(..)失敗時,它會拋出一個異常。在e.printStackTrace()上放置一個斷點;在DEBUG模式下運行並檢查你的AssertionException/Error是否被捕獲。

而不是捕捉異常,只需將所有檢查的異常添加到您的測試簽名。如果一個異常未被捕獲,它將會通過測試。另外,但在我看來,不太喜歡,通過把失敗()解決;在catch塊中。

+0

但我的代碼沒有得到錯誤,所以它不是處理異常。 – SachinB

+0

當你的assertThat()失敗時,該方法會拋出異常:-)。斷言失敗=>異常。這就是爲什麼斷言失敗失敗JUnit測試。 –

+0

就你而言,如果「matchesJsonSchemaInClassPath」不匹配,則會引發JsonSchemaValidationException。你捕捉到這個異常,而不是讓它冒泡並且通過測試。 (發現RestAssured的GITHUB頁面中的例外名稱:https://github.com/rest-assured/rest-assured) –

0

我的JSONAssert風扇,因爲這可以方便的完成比較JSONs。

只需使用.extract().response().getBody().asString()即可獲取答案的字符串表示形式。

完整的示例:

@Test 
public void getReturnsExpectedDataForMailExampleCom() throws JSONException { 
    String response = get("https://stackoverflow.com/users/[email protected]") 
     .then() 
     .statusCode(200) 
     .extract().response().getBody().asString(); 
    JSONAssert.assertEquals(
     "{\"email\":\"[email protected]\",\"locale\":\"de-DE\"}", 
     response, 
     false); 
} 

更新的缺點是完整的JSON不輸出,如果斷言失敗到標準輸出。

1

這與REST有保證並不直接相關,但我建議你看一下Karate,因爲IMO可能正是你要找的。

空手道的核心功能之一是你可以在一個步驟中完成一個完整的等於匹配的JSON有效載荷。

而且您可以輕鬆地從文件中使用JSON,這可以鼓勵在多個測試中重新使用有效負載。