用java+testng框架写一个自动化接口测试的代码
时间: 2024-06-09 15:06:30 浏览: 178
下面是一个使用Java和TestNG框架编写的自动化接口测试的示例代码:
```java
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import static org.testng.Assert.assertEquals;
public class ApiTest {
@Test
public void testGetRequest() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
RequestSpecification request = RestAssured.given();
Response response = request.get("/users");
int statusCode = response.getStatusCode();
assertEquals(statusCode, 200);
String responseBody = response.getBody().asString();
System.out.println(responseBody);
}
@Test
public void testPostRequest() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
String requestBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
request.body(requestBody);
Response response = request.post("/posts");
int statusCode = response.getStatusCode();
assertEquals(statusCode, 201);
String responseBody = response.getBody().asString();
System.out.println(responseBody);
}
@Test
public void testPutRequest() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
String requestBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
request.body(requestBody);
Response response = request.put("/posts/1");
int statusCode = response.getStatusCode();
assertEquals(statusCode, 200);
String responseBody = response.getBody().asString();
System.out.println(responseBody);
}
@Test
public void testDeleteRequest() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
RequestSpecification request = RestAssured.given();
Response response = request.delete("/posts/1");
int statusCode = response.getStatusCode();
assertEquals(statusCode, 200);
String responseBody = response.getBody().asString();
System.out.println(responseBody);
}
}
```
在上面的代码中,我们使用了RestAssured库来发送HTTP请求,并使用TestNG断言来验证响应。我们编写了四个测试用例,分别测试了GET、POST、PUT和DELETE请求。在每个测试用例中,我们都设置了请求的URL、头部、请求体,并发送请求。然后,我们验证响应的状态码和响应体,并将响应体打印到控制台中。
阅读全文