Rest Assured 中的 XmlPath 是什麼?


我們可以使用 XMLPath 找到所有 XML 節點。如果響應是 XML 格式,我們需要使用 XMLPath 下的方法。如果節點的值是整數,則必須使用 getInt 方法。

如果節點的值是字串,則必須使用 getString 方法,如果值在列表中,則可以使用 getList 方法獲取其值。我們首先將透過 Postman 對模擬 API URL 傳送 GET 請求。

使用 Rest Assured,我們將驗證其 XML 響應,其中包含科目 Rest Assured、Postman 的名稱,以及它們的價格分別為 10 和 6。

在上面的 XML 響應中,我們可以透過遍歷路徑 - books.book.author 和 books.book.pages 分別獲取 author 和 pages 節點的值。

示例 1

程式碼實現

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.xml.XmlPath;
public class NewTest {
   @Test
   void getXMLNodes() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //accept XML CONTENT as String
      String r = given().accept(ContentType.XML).when()

      //GET request
      .get("/c1d5e067-212d-4f63-be0db51751af1654")
      .thenReturn().asString();

      //object of XmlPath class
      XmlPath x = new XmlPath(r);

      //get nodes by traversing node paths
      System.out.println("Author name: " + x.getString("books.book.author"));
      System.out.println("Pages: " + x.getString("books.book.pages"));
   }
}

輸出

我們可以使用 XMLPath 的方法檢查 HTML 文件。我們首先將透過 Postman 對一個端點發送 GET 請求,並檢視響應主體。在下圖中,可以看到獲得的 title 值為 About Careers at Tutorials Point - Tutorialspoint。

端點 - https://tutorialspoint.tw/about/about_careers.htm

要從響應中獲取 html 內容,我們將使用 contentType(ContentType.HTML).extract() 方法。然後將獲得的響應主體轉換為字串。最後,我們將使用 html.head.title 方法獲取頁面標題。

示例 2

程式碼實現

import static io.restassured.RestAssured.given;
import static io.restassured.path.xml.XmlPath.CompatibilityMode.HTML;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import io.restassured.http.ContentType;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
public class NewTest {
   @Test
   public void verifyHtml() {

      //extract HTML response from endpoint
      Response r = given()
      .when()
      .get("https://tutorialspoint.tw/about/about_careers.htm")
      .then().contentType(ContentType.HTML).extract()
      .response();

      //convert xml body to string
      XmlPath p = new XmlPath(HTML, r.getBody().asString());

      //obtain html page title
      System.out.println(p.getString("html.head.title"));

      //verify title with assertion
      assertEquals(p.getString("html.head.title"), "About Careers at Tutorials Point - Tutorialspoint");
   }
}

輸出

更新於: 2021-11-17

3K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告