我正在尝试对一个模块进行单元测试(使用pytest和pytest-mock),我想要创建一个类的模拟实例,其中包含要在@pytest.fixture中使用的属性的某些值。
我想我终于在patch.object和自噬中找到了我想要的东西,但我不明白这些论点应该是什么,特别是“属性”
patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs)用模拟对象修补对象(目标)上的命名成员(属性)。
我尝试搜索patch.object()示例,但我只看到了与模拟类中方法的返回值有关的用例。
就像在这个例如,中一样,一个方法作为‘属性’参数传递给patch.object()。
对正确方向的任何帮助或暗示都将不胜感激!
发布于 2020-09-21 02:12:44
一个例子就是您正在尝试测试的方法。
因此,如果我想检查是否调用了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()https://stackoverflow.com/questions/63985264
复制相似问题