掘金 后端 ( ) • 2024-04-20 15:00

问题背景

这段时间使用开发一些Rest API相关的功能,准备做一些接口的简单测试,快速的验证一下API功能是否正常,正好觉得IntelliJ IDEA中的HTTP Client功能非常方便,它允许我们直接在编辑器中操作,正好记录一下。

解决方案

1、创建HTTP请求文件

在idea工具的Tools菜单中,选择HTTP Client,在里面选择创建一个测试请求,或者你创建一个.http.rest文件,通常在项目的src目录中,例如src/test/http/。你可以右键点击该目录,选择New -> File,然后输入文件名如api_requests.http

2、编写HTTP请求

在创建的文件中,可以编写HTTP请求。以下是几个基本请求的例子:

GET请求

http://localhost:8080/api/users发送一个GET请求,并期望JSON格式的响应。

GET http://localhost:8080/api/users
Accept: application/json

POST请求

http://localhost:8080/api/users发送一个POST请求,并期望JSON格式的响应。

POST http://localhost:8080/api/users
Content-Type: application/json
Accept: application/json

{
  "name": "John Doe",
  "email": "[email protected]"
}

PUT请求

http://localhost:8080/api/users/1发送一个PUT请求,用来更新ID为1的用户信息。

PUT http://localhost:8080/api/users/1
Content-Type: application/json
Accept: application/json

{
  "name": "Jane Doe",
  "email": "[email protected]"
}

DELETE请求

http://localhost:8080/api/users/1发送一个PUT请求,用来更新ID为1的用户信息。

DELETE http://localhost:8080/api/users/1

请求写好了之后,就是验证结果对不对问题,我们可以在控制台查看结果是否正确,只是几个接口,我们可以自己看一看,但是如果是几十个接口做测试,这再一个一个的去看,这就要了老命了,那么是不是还可以通过代码自动校验结果呢?

3、执行和验证请求

编写好请求后,你可以通过点击请求行旁边的运行图标(绿色的三角形)来执行它。执行后,IDEA会在下方的Run窗口中显示HTTP响应。

为了验证返回结果是否正确,你可以在HTTP请求下方写上一些验证条件:

GET http://localhost:8080/api/users
Accept: application/json

> {%
client.test("Request executed successfully", function() {
    client.assert(response.status === 200, "Response status is not 200");
});
client.test("Response contains users", function() {
    var jsonData = JSON.parse(response.body);
    client.assert(jsonData.length > 0, "Response does not contain a list of users");
});
%}

在上面的例子中,我们不仅发送了GET请求,还定义了一些测试来验证请求是否成功执行,以及响应体是否包含用户数据。

接下来我们列举一些常见的方法和示例:

1、校验响应状态码:使用response.status来验证HTTP响应的状态码是否符合预期值。

GET http://localhost:8080/api/users
Accept: application/json

> {% client.test("Status code is 200", function() {
    client.assert(response.status === 200, "Expected status code 200, but got " + response.status);
}); %}

2、校验响应正文内容:使用JSON.parse(response.body)来解析响应正文中的JSON,然后对其进行各种校验。

GET http://localhost:8080/api/users/1
Accept: application/json

> {% client.test("User name is John", function() {
    var responseBody = JSON.parse(response.body);
    client.assert(responseBody.name === "John", "Expected name to be John");
}); %}

3、检查响应头:使用response.headers来验证响应头中的特定值。

GET http://localhost:8080/api/users
Accept: application/json

> {% client.test("Content-Type is set to application/json", function() {
    var contentType = response.headers['Content-Type'] || response.headers['content-type'];
    client.assert(contentType.includes('application/json'), "Expected 'Content-Type' header to be 'application/json'");
}); %}

4、校验响应时间:使用response.timings来测量请求的响应时间,并确保响应足够快。

GET http://localhost:8080/api/users
Accept: application/json

> {% client.test("Response time is under 500ms", function() {
    var timeTaken = response.timings.response;
    client.assert(timeTaken < 500, "Expected response time to be under 500ms");
}); %}

5、检查响应是否包含某字符串:验证响应正文中是否包含某个特定的字符串。

GET http://localhost:8080/api/users
Accept: application/json

> {% client.test("Body contains 'John'", function() {
    client.assert(response.body.indexOf('John') !== -1, "Response body does not contain 'John'");
}); %}

6、检查数组或对象长度:验证JSONObject或JSONArray的长度与预期是否一致。

GET http://localhost:8080/api/users
Accept: application/json

> {% client.test("User list is not empty", function() {
    var responseBody = JSON.parse(response.body);
    client.assert(responseBody.length > 0, "User list should not be empty");
}); %}

最后我们使用一个完整的示例,说明一下在使用IntelliJ IDEA的HTTP Client时,如何验证响应正文中的JSON数据?

这时候通常涉及以下几个步骤:

  1. 发送HTTP请求。
  2. 接收响应正文。
  3. 将响应正文中的JSON字符串转换为JavaScript对象。
  4. 对转换后的对象进行断言测试以验证数据。
GET http://localhost:8080/api/users/1
Accept: application/json

> {% client.test("Validate user data", function() {
    var responseJson = JSON.parse(response.body);

    // 验证状态码是200
    client.assert(response.status === 200, "Expected 200 OK response");

    // 验证某个具体的属性值
    client.assert(responseJson.id === 1, "Expected user id to be 1");

    // 验证返回的JSON对象包含必要的属性
    client.assert("name" in responseJson, "Response json should include 'name' property");
    client.assert("email" in responseJson, "Response json should include 'email' property");

    // 验证属性值满足某种条件
    client.assert(responseJson.name.length > 0, "User name should not be empty");

    // 验证邮箱格式(这里采用简单的正则表达式,实际情况可能需要更严格的验证)
    client.assert(/^[^@]+@[^@]+.[^@]+$/i.test(responseJson.email), "Email format is invalid");

    // 验证数字类型的属性
    client.assert(typeof responseJson.age === 'number', "Age should be a number");

    // 验证布尔类型的属性
    client.assert(typeof responseJson.isActive === 'boolean', "isActive should be a boolean");

    // 验证返回的JSON数组
    client.assert(Array.isArray(responseJson.tags), "Tags should be an array");
    client.assert(responseJson.tags.includes("Developer"), "Tags should include 'Developer'");

    // 验证嵌套的JSON对象
    client.assert(responseJson.address.city === "New York", "User should be from New York");

}); %}

在这个例子中,这段HTTP Client脚本在IntelliJ IDEA中执行以下操作:

  1. 发送一个GET请求到URL http://localhost:8080/api/users/1,期望获取application/json格式的响应。
  2. 使用client.test()定义了一个测试用例,名称为“Validate user data”。
  3. 将响应正文的内容解析成JSON对象,赋值给变量responseJson
  4. 验证HTTP响应状态码是否是200。
  5. 验证解析出的JSON对象中id属性值是否为1。
  6. 检查JSON对象是否包含nameemail属性。
  7. 验证name属性的值是否非空。
  8. 使用正则表达式检测email属性的格式是否符合简单的电子邮件格式。
  9. 确保age属性的类型是一个数字。
  10. 确保isActive属性的类型是布尔值。
  11. 验证tags是一个数组,并且包含字符串"Developer"。
  12. 验证嵌套的JSON对象中address对象的city属性的值是否是"New York"。