Python unittest mock:通过参数化类对象模拟类函数?

时间:2015-10-26 19:09:55

标签: mocking python-unittest magicmock

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)

1 个答案:

答案 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)