This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used.
Code #1 : Testing that a function raised a ValueError exception
Code #2 : Test the exception’s value with a different approach is needed
assertRaises() method provides a convenient way to test for the presence of an exception. A common pitfall is to write tests that manually try to do things with exceptions on their own.
Code #3 : Example
The problem with such approaches is that it is easy to forget about corner cases, such as that when no exception is raised at all. To do that, an extra check for that situation needs to be added, as shown in the code below.
Code #4 :
assertRaises() method simply takes care of these details, so it is preferred to be used. The one limitation of
assertRaises() is that it doesn’t provide a means for testing the value of the exception object that’s created.
To do that, it has to be manually tested. Somewhere in between these two extremes, the assertRaisesRegex() method can be used and it allows to test for an exception and perform a regular expression match against the exception’s string representation at the same time.
Code #5 :
A little-known fact about
assertRaisesRegex() is that they can also be used as context managers.
Code #6 :
This form can be useful if the test involves multiple steps (e.g., setup) besides that of simply executing a callable.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python | Exceptional Split in String
- Writing Tests using Selenium Python
- Unit Testing in Python - Unittest
- Phyllotaxis pattern in Python | A unit of Algorithmic Botany
- Python | Unit Test Objects Patching | Set-1
- Python | Unit Test Objects Patching | Set-2
- Standard GUI Unit Converter using Tkinter in Python
- Gated Recurrent Unit Networks
- ML | Text Generation using Gated Recurrent Unit Networks
- PyCairo - How to get SVG unit?
- PyCairo - How to set SVG unit ?
- Python | Set 2 (Variables, Expressions, Conditions and Functions)
- Check multiple conditions in if statement - Python
- Selecting rows in pandas DataFrame based on conditions
- How to Drop rows in DataFrame by conditions on column values?
- Testing in Python using doctest module
- Automated software testing with Python
- Python | Testing Output to stdout
- Mutation Testing using Mutpy Module in Python
- Getting Started With Testing in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.