How does one write a unittest that fails only if a function doesn't throw an expected exception?
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is true. The raised exception typically warns the user or the calling application. You use the “raise” keyword to throw a Python exception manually.
Use TestCase.assertRaises
(or TestCase.failUnlessRaises
) from the unittest module, for example:
import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc)
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