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?
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.
assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With