如何在 Rest Assured 中使用断言验证 JSON 响应主体?
rest assureddynamic programmingprogramming
我们可以使用 Rest Assured 中的断言来验证 JSON 响应主体。这借助 Hamcrest 断言来实现。它使用 Matcher 类进行断言。
要使用 Hamcrest,我们必须在 Maven 项目的 pom.xml 中添加 Hamcrest Core 依赖项。此依赖项的链接位于以下链接中 −
https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core
我们将通过 Postman 向模拟 API 发送 GET 请求,并观察响应。
使用 Rest Assured,我们将验证响应主体中 Location 的值。
代码实现
import org.hamcrest.Matchers; import org.testng.annotations.Test; import static io.restassured.RestAssured.given; import io.restassured.RestAssured; public class NewTest { @Test public void ressponseAssertion() { //基础 URL RestAssured.baseURI = "https://run.mocky.io"; //GET 操作 given() .when().get("/v3/6c6ed634-5e78-4b80-94c7-cf17c04c7055"); then().log().all() //验证状态码为 200 .assertThat().statusCode(200) //验证主体 .body(&"Location&", Matchers.equalTo(&"Makinac Island&")) //验证标题 .header("Content-Length" , "57"); } }