PHPUnit 有 方法 可以虚拟测试数据库,但是如何测试像curl 这样的 HTTP 服务?
我的类方法获取 URL 并请求参数发送到服务器。它接收 json 形式的答案,并将该 json 发送到另一个方法来解析并返回。
我想为这个类方法创建一个 PHPUnit 测试用例。我应该向我的服务器提供真实的网址吗?服务器是否应该向此测试用例返回成功/错误消息?
不要在类的某些方法中使用
curl
连接,而是将 curl
调用包装在它自己的类中,模拟它,然后将其传递给您的类。
通过这种方式,您可以通过让模拟返回真实的
json
来测试快乐路径,还可以模拟curl错误(使模拟的行为像真正的curl
库)。
同样适用于解析部分。如果您将解析代码移至它自己的类并将其注入“主”类,那么您将能够模拟它并模拟解析错误。
对于单元测试,你永远不应该进行真正的网络调用。
import unittest
from unittest.mock import patch
from your_module_name import Connection # Replace 'your_module_name' with the actual name of your module
class TestConnection(unittest.TestCase):
@patch('requests.get')
def test_get_response_success(self, mock_requests_get):
# Set up the mock response
mock_response = mock_requests_get.return_value
mock_response.status_code = 200
mock_response.raise_for_status.return_value = None
# Create a Connection instance
connection = Connection(base_url='https://example.com', auth=('username', 'password'))
# Call the get_response method
response = connection.get_response(file_key='example_file', cob_date='2022-01-10')
# Assertions
self.assertEqual(response, mock_response)
mock_requests_get.assert_called_once_with(
'https://example.com/example_file?cob=2022-01-10&replace-cob=true',
auth=('username', 'password'),
verify=False
)
@patch('requests.get')
def test_get_response_failure(self, mock_requests_get):
# Set up the mock response for a failed request
mock_response = mock_requests_get.return_value
mock_response.status_code = 404
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError
# Create a Connection instance
connection = Connection(base_url='https://example.com', auth=('username', 'password'))
# Call the get_response method and expect an exception
with self.assertRaises(Exception) as context:
connection.get_response(file_key='example_file', cob_date='2022-01-10')
# Assertions
self.assertEqual(str(context.exception), "HTTP failed with status 404")
mock_requests_get.assert_called_once_with(
'https://example.com/example_file?cob=2022-01-10&replace-cob=true',
auth=('username', 'password'),
verify=False
)
if __name__ == '__main__':
unittest.main()