Python
unittest
assertRaises
exception-handling
testing

Python unittest - opposite of assertRaises?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

unittest does not provide a built-in assertion named something like assertNotRaises. In practice, you usually do not need one, because a test already fails automatically if an unexpected exception is raised.

The Simple Answer

If the code should run without errors, just call it and then assert on the result or side effects.

python
1import unittest
2
3
4def parse_port(value: str) -> int:
5    port = int(value)
6    if not 0 <= port <= 65535:
7        raise ValueError("port out of range")
8    return port
9
10
11class ParsePortTests(unittest.TestCase):
12    def test_valid_port(self) -> None:
13        result = parse_port("8080")
14        self.assertEqual(result, 8080)

If parse_port("8080") raises any exception, the test fails automatically. That is already the opposite behavior of assertRaises.

Why There Is No Built-In assertNotRaises

An explicit "does not raise" assertion is less useful than assertRaises because the normal execution path already covers it. In most tests, you do not just want to prove that nothing crashed. You want to prove that the code returned the right value, updated the right state, or produced the right output.

That is why ordinary assertions are usually better than a special no-exception assertion.

If You Want a Clearer Failure Message

Sometimes you want a more explicit failure message, especially when testing several inputs. In that case, wrap the call in try and use self.fail().

python
1import unittest
2
3
4class ParsePortTests(unittest.TestCase):
5    def test_valid_port_with_explicit_failure(self) -> None:
6        try:
7            result = parse_port("8080")
8        except Exception as exc:
9            self.fail(f"parse_port raised unexpectedly: {exc}")
10
11        self.assertEqual(result, 8080)

This pattern is helpful when the default traceback is not descriptive enough for the test you are writing.

A Small Helper if You Really Want One

If your codebase strongly prefers a dedicated helper, you can define one in your base test class.

python
1import unittest
2from typing import Any, Callable
3
4
5class NoExceptionTestCase(unittest.TestCase):
6    def assertNotRaises(
7        self,
8        func: Callable[..., Any],
9        *args: Any,
10        **kwargs: Any,
11    ) -> Any:
12        try:
13            return func(*args, **kwargs)
14        except Exception as exc:
15            self.fail(f"{func.__name__} raised unexpectedly: {exc}")
16
17
18class ParsePortTests(NoExceptionTestCase):
19    def test_valid_port_with_helper(self) -> None:
20        result = self.assertNotRaises(parse_port, "8080")
21        self.assertEqual(result, 8080)

This is valid, but many teams still prefer the simpler style because it keeps tests closer to standard unittest.

subTest Works Well for Many Inputs

When you want to confirm that several inputs succeed without exceptions, subTest keeps the output readable.

python
1class ParsePortTests(unittest.TestCase):
2    def test_multiple_valid_ports(self) -> None:
3        for raw in ["80", "443", "8080"]:
4            with self.subTest(raw=raw):
5                result = parse_port(raw)
6                self.assertGreaterEqual(result, 0)

If one case raises unexpectedly, unittest reports which input failed.

Focus on Behavior, Not Just Absence of Exceptions

A test that only proves "this did not crash" is often too weak. Prefer assertions that verify meaningful behavior:

  • correct return value
  • correct object state
  • expected file or network side effect
  • correct database change

No exception is usually just one part of a good test, not the full goal.

Common Pitfalls

  • Looking for a built-in assertNotRaises when plain test code already gives the same failure behavior.
  • Writing tests that only check for lack of exceptions and never verify the result.
  • Catching exceptions too broadly and hiding useful traceback information.
  • Adding a custom helper everywhere when a direct function call would be clearer.
  • Forgetting subTest when checking several success cases in one test.

Summary

  • There is no standard unittest method that is the direct opposite of assertRaises.
  • In normal tests, just call the function and let unexpected exceptions fail the test.
  • Use self.fail() inside try and except only when you want a custom failure message.
  • A custom assertNotRaises helper is possible but usually optional.
  • The best tests verify correct behavior, not only the absence of exceptions.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.