Python > Testing in Python > Unit Testing with `unittest` > Assertions

Asserting Exceptions with `assertRaises`

This example demonstrates how to use the `assertRaises` context manager in `unittest` to verify that your code raises the expected exceptions.

Raising and Asserting Exceptions

The code defines a `divide` function that raises a `ZeroDivisionError` if the denominator is zero. The `TestDivideFunction` class uses `assertRaises` to assert that the `divide` function raises a `ZeroDivisionError` when called with a zero denominator. The `test_valid_division` method checks that the division returns the correct result when valid arguments are passed.

import unittest

def divide(x, y):
    if y == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return x / y

class TestDivideFunction(unittest.TestCase):

    def test_divide_by_zero(self):
        with self.assertRaises(ZeroDivisionError):
            divide(10, 0)

    def test_valid_division(self):
        self.assertEqual(divide(10, 2), 5)

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

Concepts Behind Exception Assertions

The `assertRaises` context manager allows you to verify that a specific block of code raises a particular exception. This is essential for testing error handling logic in your code. It ensures that your code gracefully handles exceptional situations and raises the appropriate exceptions when necessary.

Real-Life Use Case

Consider a function that parses user input. You can use `assertRaises` to verify that the function raises a `ValueError` if the input is in an invalid format. This ensures that the function properly handles invalid input and prevents unexpected behavior.

Best Practices

  • Be specific about the exception type: Use `assertRaises` to assert that a specific exception is raised, rather than a generic `Exception`.
  • Test different exception scenarios: Cover all possible exception conditions that your code might encounter.
  • Write clear and concise tests: Make your exception tests easy to understand and maintain.

Interview Tip

Be prepared to explain the importance of testing exception handling in your code. Demonstrate your ability to use `assertRaises` to verify that your code raises the expected exceptions under different circumstances. Discuss the benefits of writing robust exception handling code.

When to Use `assertRaises`

Use `assertRaises` whenever you need to verify that a specific block of code raises a particular exception. This is especially important for functions that perform error handling or data validation.

Alternatives

While `assertRaises` is the standard way to assert exceptions in `unittest`, you can also use try-except blocks with `self.fail` to achieve similar results. However, `assertRaises` is generally preferred for its conciseness and readability.

Pros

  • Concise and readable syntax.
  • Ensures that the correct exception is raised.
  • Provides a clear way to test exception handling logic.

Cons

  • Requires using a context manager (with statement).

FAQ

  • What happens if the expected exception is not raised?

    If the code within the `with self.assertRaises(...)` block does not raise the expected exception, the test will fail with an error message indicating that the expected exception was not raised.
  • Can I assert the exception message?

    Yes, you can capture the exception instance using `assertRaises` and then assert its message. For example: python with self.assertRaises(ValueError) as context: int('abc') self.assertEqual(str(context.exception), "invalid literal for int() with base 10: 'abc'")