pytest
是否提供类似于unittest.mock
的功能来检查mock是否实际被调用过一次(或者使用某些参数调用过一次)
示例源代码:
my_package/my_module.py
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()
上述源代码的测试代码示例:
test_my_module.py
import pytest
from pytest_mock import mocker
from my_package.my_module import MyModule
@pytest.fixture
def mock_will_call_other_package(mocker):
mocker.patch('my_package.my_module.will_call_other_package')
@pytest.mark.usefixtures("mock_will_call_other_package")
class TestMyModule:
def test_run(self):
MyModule().run()
#check `will_call_other_package` method is called.
#Looking for something similar to what unittest.mock provide
#mock_will_call_other_package.called_once
首先,您可能不需要像
pytest_mock
这样的外部库的负担,因为pytest
已经使用integration with unittest覆盖了您您也不需要使用
usefixtures
,因为每当您需要一个fixture时,您只需要在测试方法中接收它基于您自己的代码的理想场景如下所示:
另外,如果您想确保确实对目标
MyModule.will_call_other_package
进行了修补,请按如下方式修改您的测试:你会看到类似的东西:
正如您所看到的,两个对象的
id
是相同的,这证实了我们的实验是成功的你可以试试这个:
如果要使用进行修补的夹具,可以将修补移动到夹具中:
请注意,您必须在测试中使用fixture参数。仅仅使用
@pytest.mark.usefixtures
将无法访问模拟本身。如果不需要在所有测试中访问mock(或者在fixture中使用autouse=True
),那么仍然可以使用它在类中的所有测试中有效还要注意,这里不需要
pytest-mock
,但正如@hoefling所提到的,使用它可以使fixture更可读,因为您不需要with
子句:顺便说一下:您不需要导入
mocker
。fixture是按名称查找的,如果安装了相应的插件,它将自动可用相关问题 更多 >
编程相关推荐