下面是一个使用Python编写的接口测试用例的示例:

import requests
import unittest

class TestAPI(unittest.TestCase):

    def setUp(self):
        self.url = 'http://localhost:8080/api/user'
        self.headers = {'Content-Type': 'application/json'}
        self.data = {
            'name': 'John Doe',
            'email': 'johndoe@example.com',
            'password': 'password123'
        }

    def test_create_user(self):
        response = requests.post(self.url, headers=self.headers, json=self.data)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.json()['name'], self.data['name'])
        self.assertEqual(response.json()['email'], self.data['email'])

    def test_get_user(self):
        response = requests.get(self.url + '/1', headers=self.headers)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['name'], 'John Doe')
        self.assertEqual(response.json()['email'], 'johndoe@example.com')

    def test_update_user(self):
        update_data = {
            'name': 'Jane Doe',
            'email': 'janedoe@example.com'
        }
        response = requests.put(self.url + '/1', headers=self.headers, json=update_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['name'], update_data['name'])
        self.assertEqual(response.json()['email'], update_data['email'])

    def test_delete_user(self):
        response = requests.delete(self.url + '/1', headers=self.headers)
        self.assertEqual(response.status_code, 204)

if __name__ == '__main__':
    unittest.main()

在这个示例中,我们使用unittest模块来编写测试用例。setUp()方法用于设置测试用例的基础数据,包括API的URL,请求头和请求体数据。

接下来,我们编写了四个测试用例,分别测试了创建用户、获取用户、更新用户和删除用户的API接口。每个测试用例都使用requests库发送HTTP请求,并对响应进行断言以验证API的正确性。

最后,我们使用unittest.main()函数来运行所有测试用例。运行测试用例时,unittest会自动执行setUp()方法和所有以test开头的方法,并输出测试结果。


原文地址: https://www.cveoy.top/t/topic/bJBf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录