Python 的 mock.patch 未在单元测试中修补 class
Python's mock.patch not patching class in unittest
我对在我的 python 单元测试中使用 Mock 感到困惑。我做了这个问题的简化版本:
我有这个虚拟 class 和方法:
# app/project.py
class MyClass(object):
def method_a(self):
print(FetcherA)
results = FetcherA()
哪个正在使用这个 class:
# app/fetch.py
class FetcherA(object):
pass
然后这个测试:
# 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()
我希望 运行 这个测试会通过,并且 print
语句用于调试,会输出类似于 <MagicMock name=...>
的内容。相反,它打印出 <class 'app.fetch.FetcherA'>
并且我得到:
AssertionError: Expected to be called once. Called 0 times.
为什么 FetcherA
没有被修补?
好的,第四遍我想我理解了 Mock 文档的 'Where to patch' 部分。
所以,而不是:
@patch('app.fetch.FetcherA')
我应该使用:
@patch('app.project.FetcherA')
因为我们正在测试 app.project.MyClass
中的代码,其中 FetcherA
已经导入。所以那时 FetcherA
在 app.project
.
内是全局可用的(?)
我对在我的 python 单元测试中使用 Mock 感到困惑。我做了这个问题的简化版本:
我有这个虚拟 class 和方法:
# app/project.py
class MyClass(object):
def method_a(self):
print(FetcherA)
results = FetcherA()
哪个正在使用这个 class:
# app/fetch.py
class FetcherA(object):
pass
然后这个测试:
# 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()
我希望 运行 这个测试会通过,并且 print
语句用于调试,会输出类似于 <MagicMock name=...>
的内容。相反,它打印出 <class 'app.fetch.FetcherA'>
并且我得到:
AssertionError: Expected to be called once. Called 0 times.
为什么 FetcherA
没有被修补?
好的,第四遍我想我理解了 Mock 文档的 'Where to patch' 部分。
所以,而不是:
@patch('app.fetch.FetcherA')
我应该使用:
@patch('app.project.FetcherA')
因为我们正在测试 app.project.MyClass
中的代码,其中 FetcherA
已经导入。所以那时 FetcherA
在 app.project
.