1

我正在尝试对一个模块进行单元测试(使用 pytest 和 pytest-mock),并且我想创建一个类的模拟实例,该类的属性具有某些值,以便在 @pytest.fixture 中使用

我想我终于在patch.objectautospeccing中找到了我想要的东西,但我不明白这些参数应该是什么,特别是“属性”

patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs)

使用模拟对象修补对象(目标)上的命名成员(属性)。

我尝试搜索 patch.object() 示例,但我只看到与模拟类中方法的返回值相关的用例。

就像在这个例子中一样,一个方法作为“属性”参数传递给 patch.object()。

任何正确方向的帮助或提示将不胜感激!

4

1 回答 1

1

一个示例是您尝试测试的方法。

所以,如果我想检查是否MyClass.method_a被调用,我会这样做:

from .functions import MyClass  # import MyClass from wherever 
                                # it is used in the module.


with patch.object(MyClass, 'method_a') as mocked_myclass:
    function_that_called_myclass_method_a()

mocked_myclass.assert_called()
于 2020-09-21T02:12:44.327 回答