我正在使用 Python 3.8 和 pytest 6.0.1。我有这门课
class MyHelperService:
def __init__(self, args):
...
def my_method1(self):
... logic here ...
然后在另一个类中,我调用上面的方法..
def main(req: func.HttpRequest) -> func.HttpResponse:
...
sb = MyHelperService(args)
sb.my_method1()
在 pytest 中,我如何模拟“my_method1”,以便可以测试它是否被调用,而不必执行其中的所有逻辑?
def test_run_it():
...
resp = _import.main(req)
最佳答案
假设MyHelperService
位于my_project/my_helper_service.py
中,main
位于my_project/main.py
中, 并且假设在main
中您导入了如下类:
from my_project.my_helper_service import MyHelperService
你可以像这样修补你的方法(我假设你根据评论使用另一个固定装置my_fixture
):
from unittest import mock
@mock.patch("my_project.main.MyHelperService.my_method1")
def test_run_it(method1_mock, my_fixture):
...
resp = _import.main(req)
method1_mock.assert_called_once()
这用模拟替换了method1
,该模拟仅记录所有调用而不执行原始代码。请注意,模拟参数是位置参数,因此大多数是第一个参数,而固定参数是关键字参数(必须位于位置参数之后)。
或者,您可以使用上下文管理器版本:
def test_run_it(my_fixture):
...
with mock.patch("my_project.main.MyHelperService.my_method1") as method1_mock:
resp = _import.main(req)
method1_mock.assert_called_once()
或者mocker
版本,如果你已经安装了pytest-mock
:
def test_run_it(mocker, my_fixture):
...
method1_mock = mocker.patch("my_project.main.MyHelperService.my_method1")
resp = _import.main(req)
method1_mock.assert_called_once()
一些有用的链接:
- documentation
- 这个blog post作者:内德·巴切尔德
- 这个cheat sheet用于在 Python 中进行模拟
关于python-3.x - 在 Pytest 中,如何检查一个方法是否是从另一个方法调用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63636108/