使用断言来比较API响应中的JSON结果。以下是一个Python示例:
import requests
import json
import pytest
api_url = "https://api.example.com/users"
def test_api_response():
# 发送API请求
response = requests.get(api_url)
# 将响应JSON解析为Python字典
expected_result = json.loads(response.text)
# 模拟实际场景的响应数据,假设返回的JSON结果如下:
actual_result = {
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com"
}
]
}
# 使用断言比较实际结果和期望结果
assert actual_result == expected_result
在此示例中,我们使用了Python的requests
库发送了一个API请求并将响应JSON解析为Python字典。然后,我们模拟了一个实际数据场景,并使用断言来比较实际结果和期望结果。通过这种方式,我们可以确定API是否按预期返回结果。