Testing Exceptions in Python Functions
Problem:
How to ensure that a Python function raises an expected exception?
Answer:
Use the TestCase.assertRaises method from the unittest module. This method takes two arguments: the exception class and the function call. If the function call does not raise the expected exception, the test fails.
Here's an example:
<code class="python">import unittest import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc)</code>
In this example, test1 asserts that the function myfunc in module mymod raises an exception of type SomeCoolException. If the exception is not raised, the test will fail.
The above is the detailed content of How to Test for Expected Exceptions in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!