Pass a Python unittest if an exception isn't raised

前端 未结 3 1972
再見小時候
再見小時候 2020-12-03 07:54

In the Python unittest framework, is there a way to pass a unit test if an exception wasn\'t raised, and fail with an AssertRaise otherwise?

3条回答
  •  心在旅途
    2020-12-03 08:18

    If I understand your question correctly, you could do something like this:

    def test_does_not_raise_on_valid_input(self):
        raised = False
        try:
            do_something(42)
        except:
            raised = True
        self.assertFalse(raised, 'Exception raised')
    

    ...assuming that you have a corresponding test that the correct Exception gets raised on invalid input, of course:

    def test_does_raise_on_invalid_input(self):
        self.assertRaises(OutOfCheese, do_something, 43)
    

    However, as pointed out in the comments, you need to consider what it is that you are actually testing. It's likely that a test like...

    def test_what_is_42(self):
        self.assertEquals(do_something(42), 'Meaning of life')
    

    ...is better because it tests the desired behaviour of the system and will fail if an exception is raised.

提交回复
热议问题