简体   繁体   English

如何模拟 class 实例并使用 mocker.patch.object() 和 pytest-mock 为该实例分配属性?

[英]How do I mock a class instance and assign attributes to that instance using mocker.patch.object() and pytest-mock?

I am trying to unit test a module (using pytest and pytest-mock) and I would like to create a mocked instance of a class with certain values for its attributes to be used in a @pytest.fixture我正在尝试对模块进行单元测试(使用 pytest 和 pytest-mock),我想创建一个 class 的模拟实例,其属性的某些值将在 @pytest.fixture 中使用

I think I've finally found what I'm looking for in patch.object and autospeccing but I don't understand what the arguments are supposed to be, specifically 'attribute'我想我终于在patch.objectautospeccing中找到了我要找的东西,但我不明白 arguments 应该是什么,特别是“属性”

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

patch the named member (attribute) on an object (target) with a mock object.使用模拟 object 修补 object(目标)上的命名成员(属性)。

I tried searching for patch.object() examples but I'm only seeing use cases related to mocking the return values for methods in a class.我尝试搜索 patch.object() 示例,但我只看到与 mocking 相关的用例,即 class 中方法的返回值。

Like in this example, a method is passed as the 'attribute' argument to patch.object().就像在这个例子中一样,一个方法作为“属性”参数传递给 patch.object()。

Any help or hints in the right direction would be greatly appreciated!任何正确方向的帮助或提示将不胜感激!

An example would be the method that you're trying to test.一个例子就是您要测试的方法。

So, if I wanted to check to see if MyClass.method_a was called, I would do:所以,如果我想检查是否调用了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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM