Unit Test for Expected Exception in Python

How can one write a unit test in Python that fails only if a function does not throw an expected exception?

In Python, how can I create a unit test to ensure that a function raises a specific exception? I want the test to fail only if the exception is not raised.

I am looking for a method to use python assert exception in my unit tests.

Using pytest.raises:
If you’re working with pytest, it provides a simple and effective way to assert that a function raises a specific exception. Here’s an example:

import pytest

def function_that_raises():
    raise ValueError("This is an expected error")

def test_function_raises_exception():
    with pytest.raises(ValueError, match="This is an expected error"):
        function_that_raises()

In this case, pytest.raises ensures that the function_that_raises() triggers a ValueError with the given message. The test will only fail if the exception isn’t raised or the message doesn’t match. This is a great way to ensure that your test accurately handles the python assert exception scenario.

Using unittest.TestCase.assertRaises:**
For those using the built-in unittest framework, there’s an alternative method using assertRaises. It’s a bit more structured, but does the job:

import unittest

def function_that_raises():
    raise ValueError("This is an expected error")

class TestFunction(unittest.TestCase):
    def test_function_raises_exception(self):
        with self.assertRaises(ValueError):
            function_that_raises()

if __name__ == '__main__':
    unittest.main()

Here, assertRaises from unittest.TestCase checks if the function_that_raises() throws a ValueError. If no exception is raised, the test fails. This is another approach to verifying python assert exception handling, and it’s particularly helpful for those already using unittest.

Using assert with Exception Handling:**
If you’re not using any additional testing frameworks, you can manually handle exceptions with a try-except block and an assert. Here’s how:

def function_that_raises():
    raise ValueError("This is an expected error")

def test_function_raises_exception():
    try:
        function_that_raises()
    except ValueError:
        pass  # Test passes as exception was raised
    else:
        assert False, "Expected ValueError but no exception was raised"

test_function_raises_exception()

In this method, you manually check for exceptions. If ValueError is caught, the test passes silently. If no exception occurs, the assert False ensures the test fails, making it a clean way to verify the python assert exception is handled without additional tools.