1

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中,我想在lib.thing.Class.class_function1使用模拟的 Class() 对象调用 function2 时进行修补,以引发一个AttributeError应该可以test_function2畅通无阻的 perc。像这样的东西(不起作用):

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

1 回答 1

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)
于 2015-10-26T21:35:21.440 回答