访问了模拟实例上的断言属性

时间:2013-10-02 21:37:36

标签: python unit-testing mocking

如何断言访问Mock和/或MagicMock的属性?

例如,

from unittest.mock import MagicMock

def foo(x):
    a = x.value

m = MagicMock()
foo(m)
m.attr_accessed('value')    # method that does not exist but I wish did; should return True

检查foo是否尝试访问m.value的实际方法是什么?

1 个答案:

答案 0 :(得分:10)

您可以按照here所述使用PropertyMock。

如,

from unittest.mock import MagicMock, PropertyMock

def foo(x):
    a = x.value

m = MagicMock()
p = PropertyMock()
type(m).value = p
foo(m)
p.assert_called_once_with()