由incode try..except捕获的Mox错误

时间:2017-10-15 13:16:07

标签: python python-unittest mox

请考虑以下事项:

类别:

class Something(object):
    def should_not_be_called(self):
        pass

    def should_be_called(self):
        pass

    def do_stuff(self):
        self.should_be_called()
        try:
            self.should_not_be_called()
        except Exception:
            pass

单元测试:

class TestSomething(unittest.TestCase):
    def test(self):
        mocker = mox.Mox()

        something = Something()
        mocker.StubOutWithMock(something, 'should_be_called')
        mocker.StubOutWithMock(something, 'should_not_be_called')

        something.should_be_called()

        mocker.ReplayAll()

        something.do_stuff()

        mocker.VerifyAll()

此测试将通过(当它应该明显失败时),因为do_stuff()中的try ..except除UnexpectedMethodCallError时测试运行...

有没有办法解决这个问题?

编辑: 另一个例子说明了为什么这个问题好一点:

class AnotherThing(object):
    def more_stuff()(self, num):
        if i == 2:
            raise ValueError()

    def do_stuff(self):
        for i in [1, 2, 3, 'boo']:
            try:
                self.more_stuff(i)
            except Exception:
                logging.warn("an exception might have been thrown but code should continue")


class TestAnotherThing(unittest.TestCase):
    def test(self):
        mocker = mox.Mox()

        another_thing = Something()
        mocker.StubOutWithMock(something, 'fails_on_2')
        mocker.StubOutWithMock(something, 'called_when_no_error')

        another_thing.more_stuff(1)
        # actual function calls more_stuff 2 more times, but test will still pass 
        another_thing.more_stuff('boo')

        mocker.ReplayAll()

        another_thing.do_stuff()

        mocker.VerifyAll()

0 个答案:

没有答案