<p>首先,您可能不需要像<code>pytest_mock</code>这样的外部库的负担,因为<code>pytest</code>已经使用<a href="https://docs.pytest.org/en/latest/how-to/unittest.html#unittest" rel="nofollow noreferrer">integration with unittest</a>覆盖了您</p>
<p>您也不需要使用<code>usefixtures</code>,因为每当您需要一个fixture时,您只需要在测试方法中接收它</p>
<p>基于您自己的代码的理想场景如下所示:</p>
<pre><code>import pytest
from unittest.mock import patch
from com.abc.validation import Validation
class MyModule:
def __init__(self):
pass
def will_call_other_package(self):
val = Validation()
val.do()
def run(self):
self.will_call_other_package()
@pytest.fixture
def call_other_module():
with patch("my_package.my_module.MyModule.will_call_other_package") as _patched:
yield _patched
class TestMyModule:
def test_run_will_call_other_package(self, call_other_module):
call_other_module.assert_not_called()
obj = MyModule()
call_other_module.assert_not_called()
obj.run()
call_other_module.assert_called_once()
</code></pre>
<p>另外,如果您想确保确实对目标<code>MyModule.will_call_other_package</code>进行了修补,请按如下方式修改您的测试:</p>
<pre><code>class TestMyModule:
def test_run_will_call_other_package(self, call_other_module):
call_other_module.assert_not_called()
obj = MyModule()
call_other_module.assert_not_called()
obj.run()
call_other_module.assert_called_once()
assert False, (MyModule.will_call_other_package, call_other_module)
</code></pre>
<p>你会看到类似的东西:</p>
<pre><code>AssertionError: (<MagicMock name='will_call_other_package' id='140695551841328'>, <MagicMock name='will_call_other_package' id='140695551841328'>)
</code></pre>
<p>正如您所看到的,两个对象的<code>id</code>是相同的,这证实了我们的实验是成功的</p>