Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I test that a function raises the expected exception?

Quick answer

In Python’s unittest framework, put the invalid function call inside with self.assertRaises(ExpectedError):. The test checks for that expected exception type rather than treating any failure as success. Keep the context focused on the call you expect to fail; setup or other code inside it could otherwise raise the exception and make the test misleading. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a function that should reject an invalid value. How do I test that it raises the right exception with unittest?

Geez

Use assertRaises as a context manager and put the invalid call inside it. For example, suppose parse_count is intended to reject negative counts with ValueError:

import unittest


def parse_count(value):
    if value < 0:
        raise ValueError("count must not be negative")
    return value


class ParseCountTests(unittest.TestCase):
    def test_negative_count_raises_value_error(self):
        with self.assertRaises(ValueError):
            parse_count(-1)

Here, the test expects a ValueError from parse_count(-1). unittest.TestCase.assertRaises supports this context-manager form for checking an expected exception. [S1]

Follow-up question

Why not just put the whole test method inside assertRaises? Wouldn't that still catch the error?

Geez

It could catch an exception from the wrong part of the test. For example, if setup code raises ValueError before the function call, a broad context could make the test appear to pass even though the function was never tested. Keep only the call expected to fail inside the context:

with self.assertRaises(ValueError):
    parse_count(-1)

Do any setup before that block, and put later assertions after it. The focused form makes the test’s intent easier to inspect. The documented context-manager pattern likewise places the invalid call inside assertRaises. [S1]

Follow-up question

How can I make sure the test isn’t passing just because some other exception happened?

Geez

Name the expected exception type explicitly, such as ValueError, rather than catching a broad category like Exception. Then an unrelated exception type does not satisfy the expected-exception check. For instance, this test says which failure is part of the function’s behavior:

with self.assertRaises(ValueError):
    parse_count(-1)

Avoid wrapping unrelated operations in the same block. unittest distinguishes failed assertions from other exceptions it reports as errors, so an unexpected failure should not be treated as a successful assertion. [S1] This test checks the exception type; it does not by itself verify the exception message or every other behavior of the function.

Follow-up question

What should I include when I add this test to a larger test file?

Geez

Choose one invalid input whose expected behavior you want to protect, and give the test a name that says what should happen. Keep the sample small: arrange any required objects first, then make the single invalid call inside assertRaises. If the function has several distinct invalid-input cases, separate tests can make it clear which case failed. The example above is illustrative; substitute your function, input, and documented exception type. This pattern verifies that the call raises the specified type, but does not establish that the function behaves correctly for all inputs.

A practical checklist

  • Choose the specific invalid input the test is meant to cover.

  • Use the exception type the function is expected to raise.

  • Put only the invalid function call inside with self.assertRaises(...).

  • Keep setup and unrelated assertions outside the context.

  • Use a test name that describes the invalid case and expected exception.

A few more useful answers

Does this test check the exception message too?

The example checks that the call raises the specified exception type. It does not check the exception message; add a separate assertion if that detail matters.

What if the function is not supposed to raise an exception?

Call it normally in a test and check its expected result. Do not put that call inside assertRaises, which is for calls expected to raise an exception. [S1]

Does one passing exception test prove all invalid inputs are handled?

No. It shows that the tested call raised the specified exception type. Add separate focused cases for other invalid inputs or behaviors you need to check.

Sources

References used for this guide.

  1. [S1] Python unittest: TestCase assertions and exception checks
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work