如何在 Rest Assured 中将 TestNG 断言融入到响应验证中?
rest assureddynamic programmingprogramming更新于 2025/4/5 16:37:17
我们可以在 Rest Assured 中将 TestNG 断言融入到响应验证中。要使用 TestNG,我们需要在 Maven 项目的 pom.xml 中添加以下依赖项。此依赖项的链接可在以下链接中找到 −
https://mvnrepository.com/artifact/org.testng/testng
要使用 TestNG 断言验证响应,我们需要使用 Assert 类的方法。我们首先通过 Postman 向模拟 API URL 发送 GET 请求,并查看响应。
示例
使用 Rest Assured 和 TestNG,我们将验证 Course 字段的值,该字段为自动化测试。
代码实现
import org.testng.Assert; import org.testng.annotations.Test; import static io.restassured.RestAssured.*; import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import io.restassured.response.ResponseBody; import io.restassured.specification.RequestSpecification; public class NewTest { @Test void verifyTestNg() { String c = "Automation Testing"; //包含 Rest Assured 类的基本 URI RestAssured.baseURI = "https://run.mocky.io/v3"; //输入详细信息 RequestSpecification h = RestAssured.given(); //获取响应 Response r = h.get("/e3f5da9c-6692-48c5-8dfe-9c3348cfd5c7"); //响应主体 ResponseBody bdy = r.getBody(); //将响应主体转换为字符串 String b = bdy.asString(); //响应主体的 JSON 表示形式 JsonPath j = r.jsonPath(); //获取 Location 键的值 String l = j.get("Course"); System.out.println("Course name: " + l); Assert.assertEquals(l, c); } }