我正在使用Python的mock
库。我知道如何按照文档来模拟一个类实例方法:
>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
然而,尝试模拟一个类实例变量却不起作用(在下面的示例中是instance.labels
):
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
基本上我想让
some_function
下的instance.labels
得到我想要的值。有什么提示吗?
instance.labels = [1, 1, 2, 2]
相同的结果,这意味着这个模拟变量没有被some_function
使用。在文档中,它是模拟方法而不是变量。 - clwenlabels
只会在调用某个函数后出现。而且这个函数是在我想要测试的函数内部被调用的。也许这就是原因。最终我选择模拟类的初始化,以便返回我想要的行为的模拟对象。 - clwen