我希望测试一个http post方法,该方法将调用一些服务,但这些服务在本地测试机上无法正常工作,因此我想模拟它。
test.py:
@route(bp, '/count', methods=['POST'])
def count():
from module import service
...
total, ids = service(id, page, count) // total is a integer, ids is a list.
...
return {'total': total, 'ids': ids}
测试案例:
@mock.patch("module.service")
def test_search_user(self, mock_service):
mock_service.return_value=(1, [])
url = url_for('users.count')
params = { .... }
response = self._test_app.post_json(
url, params, headers=self.request_headers, expect_errors=True)
self.assertEqual(response.status_code, 200)
但测试用例总是失败,它试图调用service
方法,但它在我的机器上无法工作。我只想模拟它,但不起作用。
有人可以帮帮我!提前致谢!
根据@syntonym的答案,我的测试用例应该这样写:
@mock.patch("test.service")
def test_search_user(self, mock_service):
mock_service.return_value=(1, [])
service
应该被替换为magickmock
吗?service
是从哪里来的?阅读此处关于在哪里打补丁的内容。 - syntonymservice
。 - pangpangtestmodule
中的service
引用模拟对象,则需要打补丁@mock.patch("testmodule.service")
,而不是module.service
。有关更多信息,请阅读此文档。 - syntonym