9
我正在使用Python的mock
库。我知道如何通过遵循document嘲笑一个类的实例方法:Python模拟类实例变量
>>> 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'
基本上我想instance.labels
根据some_function
得到我想要的值。任何提示?
它不起作用。我得到了与'instance.labels = [1,1,2,2]'相同的结果,这个模拟变量没有被'some_function'使用。在文档中,它嘲笑方法而不是变量。 – clwen
更新了我的答案。现在我迷路了,因为你的代码正在工作。 – twil
在我的代码中,只有在调用某个函数后才会出现'labels'。该函数在我想测试的函数中调用。也许这就是原因。我最终模拟了类的初始化,以便它返回具有我想要的行为的模拟对象。 – clwen