如何为调用requests.post的无返回值函数编写单元测试?
解决无返回值函数的单元测试问题
针对你这个无返回值的post_this函数,用mock验证requests.post的调用是完全可行的,大概率是你mock的路径不对或者断言参数有偏差。下面给你两种常用测试框架的正确实现方式:
方式一:使用Python标准库unittest.mock
假设你的函数放在my_module.py中,测试代码可以这么写:
import unittest from unittest.mock import patch from my_module import post_this class TestPostThis(unittest.TestCase): @patch('my_module.requests.post') # 注意这里要mock函数所在模块里的requests.post,不是全局的requests.post def test_post_this_calls_requests_post_correctly(self, mock_post): # 准备测试参数 test_url = "https://example.com/api" test_data = {"key": "value"} test_headers = {"Content-Type": "application/json"} # 调用待测试函数 post_this(test_url, test_data, test_headers) # 验证requests.post是否被正确调用 mock_post.assert_called_once_with( test_url, json=test_data, headers=test_headers ) if __name__ == '__main__': unittest.main()
方式二:使用pytest配合pytest-mock
如果用pytest的话,代码会更简洁:
from my_module import post_this def test_post_this_calls_requests_post_correctly(mocker): # mock requests.post mock_post = mocker.patch('my_module.requests.post') # 准备参数并调用函数 test_url = "https://example.com/api" test_data = {"key": "value"} test_headers = {"Content-Type": "application/json"} post_this(test_url, test_data, test_headers) # 验证调用 mock_post.assert_called_once_with( test_url, json=test_data, headers=test_headers )
关键注意点
- mock路径必须正确:一定要mock
post_this函数所在模块中导入的requests.post,而不是直接mock全局的requests.post。因为Python会优先使用函数所在模块的本地引用,路径错了mock就不会生效。 - 参数匹配要完全一致:
assert_called_once_with会严格匹配所有参数,包括关键字参数的名称(比如你函数里用的是json=data,断言时不能写成data=test_data),如果参数有偏差也会断言失败。
内容的提问来源于stack exchange,提问作者Bash----
相关产品推荐
相关产品推荐

