我在python单元测试中使用Mock感到困惑.我已经制作了我的问题的简化版本:
我有这个虚拟类和方法:
# app/project.py
class MyClass(object):
def method_a(self):
print FetcherA
results = FetcherA()
Run Code Online (Sandbox Code Playgroud)
哪个使用这个类:
# app/fetch.py
class FetcherA(object):
pass
Run Code Online (Sandbox Code Playgroud)
然后这个测试:
# app/tests/test.py
from mock import patch
from django.test import TestCase
from ..project import MyClass
class MyTestCase(TestCase):
@patch('app.fetch.FetcherA')
def test_method_a(self, test_class):
MyClass().method_a()
test_class.assert_called_once_with()
Run Code Online (Sandbox Code Playgroud)
我希望运行此测试将通过,并且该print语句,为了调试,将输出类似的东西<MagicMock name=...>.相反,它打印出来<class 'app.fetch.FetcherA'>,我得到:
AssertionError: Expected to be called once. Called 0 times.
Run Code Online (Sandbox Code Playgroud)
为什么不FetcherA修补?
好的,第四次通过我认为我理解了Mock文档的"Where to patch"部分.
所以,而不是:
@patch('app.fetch.FetcherA')
Run Code Online (Sandbox Code Playgroud)
我应该用:
@patch('app.project.FetcherA')
Run Code Online (Sandbox Code Playgroud)
因为我们正在测试中的代码app.project.MyClass,其中FetcherA已经被导入.所以在那一点FetcherA上有效地在全球范围内(?)app.project.