在lib/thing.py
:
class Class(object):
def class_function1(self):
在app/thing.py
:
def function2(class_object):
class_object.class_function1()
在test/test_thing.py
中,我想在使用模拟的Class()对象调用function2时修补lib.thing.Class.class_function1
以引发AttributeError
,这应该只是test_function2
不受阻碍。像这样的东西(不起作用):
def test_function2(self):
mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
with assertRaises(AttributeError):
with patch ('lib.thing.Class.class_function1', side_effect=AttributeError):
function2(mocked_class)
答案 0 :(得分:1)
我完全删除了补丁,并在模拟的类对象中使用了side_effect。
def test_function2(class_object):
mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
mocked_class.class_function1.side_effect = AttributeError("sorry for the pseudo code")
with assertRaises(AttributeError):
function2(mocked_class)