Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用提供的用户值模拟类属性?_Python_Mocking_Pytest_Patch - Fatal编程技术网

Python 如何使用提供的用户值模拟类属性?

Python 如何使用提供的用户值模拟类属性?,python,mocking,pytest,patch,Python,Mocking,Pytest,Patch,我想模拟测试中的class属性 课程安排如下: import path.to.some.other.class.OtherClass class ClassToTest: def __init__(self, some_path): self._attribute_to_test = OtherClass(some_other_path) #rest of the class details .. 我试图编写的单元测试如下(但没有按预期工作): 现在,当

我想模拟测试中的class属性

课程安排如下:

import path.to.some.other.class.OtherClass
class ClassToTest:
   def __init__(self, some_path):
    self._attribute_to_test = OtherClass(some_other_path)
    
    #rest of the class details
    ..
我试图编写的单元测试如下(但没有按预期工作):


现在,当我尝试实例化ClassToTest时,属性
attribute\u to\u test
不会模拟。

\u attribute\u to\u test
似乎是一个实例属性,而不是类属性,所以这不起作用。无论如何,不需要明确地设置属性-如果您正确地模拟了其他类,则应使用模拟对其进行初始化。相反,您必须将
return\u value
设置为所需的值。我尝试使用
\u mock.return\u value=some\u value
模拟
OtherClass
,但在稍后通过ClassToTest进行调试时,步骤
OtherClass(some\u other\u路径)
不显示mock类型,但仍坚持其原始符号。我想我真的不理解如何模拟对象的模拟概念,那么你可能只是模拟了错误的对象,检查。
with patch("path.to.some.other.class.OtherClass") as _mock:
    instance = _mock.return_value
    ClassToTest._attribute_to_test = instance