擅长:python、mysql、java
<p>如果要使用进行修补的夹具,可以将修补移动到夹具中:</p>
<pre class="lang-py prettyprint-override"><code>import pytest
from unittest import mock
from my_package.my_module import MyModule
@pytest.fixture
def mock_will_call_other_package():
with mock.patch('my_package.my_module.will_call_other_package') as mocked:
yield mocked
# the mocking will be reverted here, e.g. after the test
class TestMyModule:
def test_run(self, mock_will_call_other_package):
MyModule().run()
mock_will_call_other_package.assert_called_once()
</code></pre>
<p>请注意,您必须在测试中使用fixture参数。仅仅使用<code>@pytest.mark.usefixtures</code>将无法访问模拟本身。如果不需要在所有测试中访问mock(或者在fixture中使用<code>autouse=True</code>),那么仍然可以使用它在类中的所有测试中有效</p>
<p>还要注意,这里不需要<code>pytest-mock</code>,但正如@hoefling所提到的,使用它可以使fixture更可读,因为您不需要<code>with</code>子句:</p>
<pre class="lang-py prettyprint-override"><code>@pytest.fixture
def mock_will_call_other_package(mocker):
yield mocker.patch('my_package.my_module.will_call_other_package')
</code></pre>
<p>顺便说一下:您不需要导入<code>mocker</code>。fixture是按名称查找的,如果安装了相应的插件,它将自动可用</p>