在 Rest Assured 中驗證 JSON Schema。


我們可以在 Rest Assured 中驗證 JSON Schema。Schema 驗證確保從請求獲得的響應滿足一組預先構建的規則,並且響應中的 JSON 主體具有特定的格式。

我們將使用 matchesJsonSchema 方法(JSONSchemaValidator 類的一部分)來驗證 Schema。要使用 JSON Schema 驗證,我們必須在 Maven 專案的 pom.xml 中新增額外的 JSON Schema 驗證器依賴項 -

https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator

我們首先將透過 Postman 在端點上傳送 GET 請求: https://jsonplaceholder.typicode.com/posts/2 並觀察其響應。

通常,JSON 響應的 Schema 由開發人員提供。但是,我們也可以藉助線上資源(連結如下)生成一個:https://www.liquid-technologies.com/online-json-to-schema-converter

啟動此應用程式後,我們將獲得一個名為“示例 JSON 文件”的欄位。在這裡,我們必須新增要驗證其 Schema 的 JSON 主體。然後點選“生成 Schema”按鈕。

然後,JSON 的相應 Schema 將在頁面底部生成。

讓我們建立一個 JSON 檔案,例如 schema.json,在下面新增生成的 Schema。這是在專案中建立的。

{
   "$schema": "http://json-schema.org/draft-04/schema#",
   "type": "object",
   "properties": {
      "userId": {
         "type": "integer"
      },
      "id": {
         "type": "integer"
      },
      "title": {
         "type": "string"
      },
      "body": {
         "type": "string"
      }
   },
   "required": [
      "userId",
      "id",
      "title",
      "body"
   ]
}

示例

程式碼實現

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import java.io.File;
import io.restassured.RestAssured;
import io.restassured.module.jsv.JsonSchemaValidator;
public class NewTest {
   @Test
   public void validateJSONSchema(){

      //base URL
      RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts/2";

      //obtain response
      given()
      .when().get()

      //verify JSON Schema
      .then().assertThat()
      .body(JsonSchemaValidator.
      matchesJsonSchema(new File("/Users/src/Parameterize/schema.json")));
   }
}

輸出

更新於:2021 年 11 月 17 日

13K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告