def run_test(self):
    try:
        myFunc()
    except ExceptionType:
        self.fail("myFunc() raised ExceptionType unexpectedly!")
Answer from DGH on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › test-if-a-function-throws-an-exception-in-python
Test if a function throws an exception in Python - GeeksforGeeks
July 15, 2025 - This is useful when we have to perform additional checks on the exception raised. We write a unittest that fails if no exception is raised by a function or when an exception raised by assert statement is different from expected exception.
🌐
TutorialsPoint
tutorialspoint.com › unittest_framework › unittest_framework_exceptions_test.htm
UnitTest Framework - Exceptions Test
Python testing framework provides the following assertion methods to check that exceptions are raised. Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.
Discussions

unit testing - Python unittest - opposite of assertRaises? - Stack Overflow
That's the default assumption -- exceptions are not raised. If you say nothing else, that's assumed in every single test. You don't have to actually write an any assertion for that. ... @IndradhanushGupta Well the accepted answer makes the test more pythonic than this one. More on stackoverflow.com
🌐 stackoverflow.com
unit testing - Test to check that executing a function does not raise an exception - Software Engineering Stack Exchange
If your testing framework forces ... well, Python has pass for precisely this situation. ... The usual practice is to test that result, and to test that no unexpected excecptions are thrown. ... @Mencia: what I already wrote above: test the result (keys and values), and no exceptions... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 11, 2020
unit testing - How do you test that a Python function throws an exception? - Stack Overflow
How does one write a unit test that fails only if a function doesn't throw an expected exception? More on stackoverflow.com
🌐 stackoverflow.com
unit testing - Pass a Python unittest if an exception isn't raised - Stack Overflow
In the Python unittest framework, is there a way to pass a unit test if an exception wasn't raised, and fail with an AssertRaise otherwise? ... I've only found the need to do this when testing legacy code and putting up a bunch of sanity tests. These are tests without any Asserts (basically verifying that the code block executes without blowing up). Any unexpected exceptions fail the test anyway - not ... More on stackoverflow.com
🌐 stackoverflow.com
March 18, 2015
🌐
Python
docs.python.org › 3 › library › unittest.html
unittest — Unit testing framework
Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.
🌐
Codecademy
codecademy.com › learn › learn-intermediate-python-3-exceptions-and-unit-testing › modules › unit-testing-course › cheatsheet
Learn Intermediate Python 3: Exceptions and Unit Testing: Unit Testing Cheatsheet | Codecademy
In the code example, the assertRaises() test calls the raise_index_error() function. If an IndexError exception is raised, the test passes. If any other type of exception is raised or if no exception is raised, the test will fail. ... In Python’s unittest framework, test fixtures can be created by adding setUpClass() and tearDownClass() methods to the TestCase child class.
Find elsewhere
🌐
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
There’s an alternate form of the pytest.raises() function where you pass a function that will be executed with the given *args and **kwargs and assert that the given exception is raised: pytest.raises(ExpectedException, func, *args, **kwargs) The reporter will provide you with helpful output in case of failures such as no exception or wrong exception.
🌐
Medium
medium.com › data-science › python-exception-testing-clean-and-effective-methods-86799da86b90
Python Exception Testing: Clean and Effective Methods | by Naomi Kriger | TDS Archive | Medium
July 24, 2023 - In this tutorial, we will explore practical and effective methods to test Python code that raises and does not raise exceptions, verifying the accuracy of the exception messages, and covering both pytest and unittest, with and without parameterized tests for each framework.
🌐
Miguendes
miguendes.me › how-to-check-if-an-exception-is-raised-or-not-with-pytest
How to Check if an Exception Is Raised (or Not) With pytest
January 21, 2022 - Learn how to use pytest.raises to assert when an exception is raised or to assert no exception is raised, check the error and the exception message.
🌐
Towards Data Science
towardsdatascience.com › home › latest › python exception testing: clean and effective methods
Python Exception Testing: Clean and Effective Methods | Towards Data Science
January 22, 2025 - In this tutorial, we will explore practical and effective methods to test Python code that raises and does not raise exceptions, verifying the accuracy of the exception messages, and covering both pytest and unittest, with and without parameterized tests for each framework.
🌐
Python Clear
pythonclear.com › home › unittest › 2 ways to use python unittest assertraises() in python
2 Ways to use Python Unittest assertRaises() in Python - Python Clear
December 29, 2023 - Returns: The return value from calling callable (or None if an exception is not raised). Let’s start with a very simple example for Python unittest assertraises.
🌐
GeeksforGeeks
geeksforgeeks.org › python-exceptional-conditions-testing-in-unit-tests
Python | Exceptional Conditions Testing in Unit Tests - GeeksforGeeks
June 12, 2019 - When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i ... The unittest unit testing framework is used to validate that the code performs as designed.
🌐
pytest
docs.pytest.org › en › 6.2.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
There’s an alternate form of the pytest.raises() function where you pass a function that will be executed with the given *args and **kwargs and assert that the given exception is raised: pytest.raises(ExpectedException, func, *args, **kwargs) The reporter will provide you with helpful output in case of failures such as no exception or wrong exception.
🌐
Reddit
reddit.com › r/django › exception not raised in unit test
r/django on Reddit: Exception not raised in Unit Test
May 7, 2021 -

In my code, I'm raising an exception if a certain condition is met. However, when writing my unit tests, I'm getting an error that the exception is not raised.

Below is a pseudo example of the code

def API_Endpoint():
    if x==y:
        raise InvalidValueException()

def api_test(self):
    url = api_endpoint
    data = {"x":y}
    with self.assertRaises(InvalidValueException):
        response = self.client.post(url=url, data=data)

I can't figure out why this is failing. if I print the response.json(), it shows

{'type': 'InvalidValueException', 'detail': {'non_field_errors': ['exception message.']}, 'fallback_message': 'exception message.'}

A subsequent test of

self.assertEquals(response.status_code, HTTP_400_BAD_REQUEST)

passes. So how come the with self.assertRaises() is failing?

🌐
Pytest with Eric
pytest-with-eric.com › introduction › pytest-assert-exception
How To Test Python Exception Handling Using Pytest Assert (A Simple Guide) | Pytest with Eric
March 23, 2026 - Test custom exceptions handling in Pytest, including multiple assertions in the same test ... To easily follow along and achieve the above objectives, the following is recommended as a basic requirement · Basic knowledge of the Python programming language