如何断言访问了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的实际方法是什么?

最佳答案

您可以使用propertymock,如here所述。
例如。,

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()

10-06 05:14