1

考虑以下:

班级:

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

这个测试将通过(当它显然应该失败时)作为 try..except in do_stuff()will 除了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()
4

0 回答 0