python 如何模拟一个方法?
python how to mock a method?
我想测试一个httppost方法,这个方法会调用一些服务,但是这个服务不能在本地测试机上运行,所以我想模拟它。
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, [])
@mock.patch
实际上采用查找名称 - 而不是您要修补的对象实际所在的位置。 The documentation reads:
patch() works by (temporarily) changing the object that a name points to with another one. [...]
The basic principle is that you patch where an object is looked up,
which is not necessarily the same place as where it is defined.
我想测试一个httppost方法,这个方法会调用一些服务,但是这个服务不能在本地测试机上运行,所以我想模拟它。
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, [])
@mock.patch
实际上采用查找名称 - 而不是您要修补的对象实际所在的位置。 The documentation reads:
patch() works by (temporarily) changing the object that a name points to with another one. [...] The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.