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

do_stuff()このテストは、try..except in will except the UnexpectedMethodCallErrorwhile the test runs...として合格します (明らかに失敗するはずの場合) 。

これを回避する方法はありますか?

編集:これが問題である理由をよりよく示す別の例:

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