如何在 Rest Assured 中处理静态 JSON?
我们可以在 Rest Assured 中处理静态 JSON。这可以通过将整个 JSON 请求存储于外部文件中来完成。首先,该文件的全部内容应当转换为 String。
然后,我们应当读取文件内容,并将其转换为 Byte 数据类型。一旦全部数据转换为 Byte,我们最终应当将其转换为字符串。我们将使用一个外部 JSON 文件作为执行 POST 请求的有效负载。
让我们创建一个 JSON 文件,叫作 payLoad.json,并在下方 JSON 格式中添加一个请求主体。这是在项目内创建的。
{
"title": "API Automation Testing",
"body": "Rest Assured",
"userId": "100"
}
示例
代码实现
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import io.restassured.RestAssured;
public class NewTest {
@Test
void readJSONfile() throws IOException {
//read data from local JSON file then store in byte array
byte[] b = Files.readAllBytes(Paths.get("payLoad.json"));
//convert byte array to string
String bdy = new String(b);
//base URL
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
//input details with header and body
given().header("Content-type", "application/json").body(bdy)
//adding post method
.when().post("/posts").then().log().all()
//verify status code as 201
.assertThat().statusCode(201);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP