Python Django Mock未按预期工作

Python Django Mock未按预期工作,python,django,mocking,django-testing,python-mock,Python,Django,Mocking,Django Testing,Python Mock,我在和django mock斗争;我甚至简化了一个单元测试,但测试仍然失败。我想验证是否调用了方法(即使使用任何参数),但“assert\u called\u once\u with”始终返回False。 目前我正在尝试: @patch('utils.make_reset_password') def test_shouldHaveCalledMakeResetToken(self, mocked): user = User.get(...) make_reset_passwor

我在和django mock斗争;我甚至简化了一个单元测试,但测试仍然失败。我想验证是否调用了方法(即使使用任何参数),但“assert\u called\u once\u 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\u app.utils.make\u reset\u password')
,然后在测试中调用调用
make\u reset\u 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)
编辑

我想到的另一件事是你没有嘲笑正确的函数。如果从另一个模块中的
utils
导入了
make\u reset\u password
,则您需要在
@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)

您在测试本身中调用
make\u reset\u password
,那么为什么要模拟它呢?正如我所说,我简化了测试。这不是我想要测试的,但我总是得到“调用0次”错误,所以我通过在测试中调用方法来简化它。。。“调用0次”错误没有改变。你能用你想测试的代码更新问题吗?我想确保,给定一个API调用,模拟方法被调用。所以我在用ApicClient进行测试调用,但是我得到了我解释的错误。所以我简化了测试,但即使我在测试中调用mock方法,测试也会一直说它没有被调用谢谢!现在它工作正常了,问题在于我在@patch方法上使用的路径;用你在例子中解释的方法解决了我的问题。非常感谢!