Python 如何使用提供的用户值模拟类属性?
我想模拟测试中的class属性 课程安排如下: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 .. 我试图编写的单元测试如下(但没有按预期工作): 现在,当
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