我正在与 django 模拟作斗争;我什至简化了单元测试,但测试仍然失败。我想验证是否调用了一个方法(即使使用任何参数),但“assert_used_once_with”始终返回 False。 目前我正在尝试:
@patch('utils.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mocked):
user = User.get(...)
make_reset_password(user)
mocked.assert_called_once_with(user)
即使这个简单的例子也失败了:
AssertionError: Expected 'make_reset_password' to be called once. Called 0 times
这怎么可能?我做错了什么?
提前致谢
最佳答案
您必须使用utils
的完整路径,例如@patch('my_app.utils.make_reset_password')
,然后在测试中调用一个调用 make_reset_password
的函数。
@patch('my_app.utils.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mock_make_reset_password):
user = User.get(...)
function_under_test(user)
mock_make_reset_password.assert_called_once_with(user)
编辑
我想到的另一件事是你没有 mock 正确的功能。如果 make_reset_password
是从另一个模块中的 utils
导入的,那么您需要更改 @patch
装饰器中的路径。
例如
# my_module.py
from my_app.utils import make_reset_password
def run_make_reset_password(user):
make_reset_password(user)
# tests.py
@patch('my_app.my_module.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mock_make_reset_password):
user = User.get(...)
run_make_reset_password(user)
mock_make_reset_password.assert_called_once_with(user)
关于python - Django 模拟未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49608352/