2
我想測試一個http post方法,這個方法會調用一些服務,但是這個服務不能在本地測試機器上工作,所以我想嘲笑它。python如何模擬一個方法?
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, [])
因此,您的第一個片段中的「服務」應該被magickmock替換? 「服務」從哪裏來? [閱讀關於在哪裏修補](https://docs.python.org/3/library/unittest.mock.html#where-to-patch) – syntonym
看看我的更新。我在模塊中定義了「服務」。 – pangpang
補丁在名稱上工作,而不是在實際的類上。所以如果你想'testmodule'中的'service'引用模擬,你需要修補'@ mock.patch(「testmodule.service」)',而不是'module.service'。有關更多信息,請閱讀[this](https://docs.python.org/3/library/unittest.mock.html#where-to-patch)。 – syntonym