gpt4 book ai didi

python-3.x - pytest - 在构造函数中模拟构造函数

转载 作者:行者123 更新时间:2023-12-04 02:46:24 26 4
gpt4 key购买 nike

全部,

我有一堂类似的课。

from mod import Bar

class Foo:
def __init__(self):
self.obj = Bar()

我如何模拟 Bar使用 pytest/pytest-mock 的构造函数?我尝试了以下失败。
def test():
with mock.patch('mod.Bar') as patched:
Foo()

最佳答案

您必须修补名称,而不是实例。

来自官方 Python 文档:Where to patch

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.



在您的示例中,您的类(class) Foo在模块 foomod.py 中定义,所以你必须修补 foomod.Bar而不是 mod.Bar .

您可以使用 mocker 将其放入 fixture 中来自 pytest-mock 的 fixture 或与 unittest.mock.patch .

@pytest.fixture # With pytest-mock
def mock_bar(mocker):
return mocker.patch('foomod.Bar')

@pytest.fixture # With stdlib
def mock_bar():
with patch('foomod.Bar') as mock:
yield mock

# Usage
def test_foo(mock_bar):
pass

据我所知,这两种方法之间没有显着差异。当 fixture 超出范围时,两者都会被清理。

关于python-3.x - pytest - 在构造函数中模拟构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com