可以使用Python中的unittest框架中assertCountEqual方法来解决这个问题。这个方法可以比较两个数组,而且不关心元素的顺序。以下是示例代码:
import unittest
import json
class TestAPI(unittest.TestCase):
def setUp(self):
self.expected_response = [
{"id": 1, "name": "Alice", "age": 23},
{"id": 2, "name": "Bob", "age": 32},
{"id": 3, "name": "Charlie", "age": 27}
]
self.api_response = [
{"id": 3, "name": "Charlie", "age": 27},
{"id": 2, "name": "Bob", "age": 32},
{"id": 1, "name": "Alice", "age": 23}
]
def test_api_response(self):
self.assertCountEqual(self.expected_response, self.api_response)
if __name__ == '__main__':
unittest.main()
在这个示例中,我们使用了setUp方法来定义了预期响应expected_response和API响应api_response。在test_api_response测试方法中,我们使用了assertCountEqual方法来比较两个数组。由于这个方法不关心元素的顺序,所以即使两个数组的元素顺序不同,这个测试也会通过。