Home >Backend Development >Python Tutorial >How to Test for Expected Exceptions in Python Functions?

How to Test for Expected Exceptions in Python Functions?

DDD
DDDOriginal
2024-11-04 02:24:02670browse

How to Test for Expected Exceptions in Python Functions?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn