If you are using Python 2.7 or above, you can use the ability of assertRaises to be used as a context manager and do:

with self.assertRaises(TypeError):
    self.testListNone[:1]

If you are using Python 2.6, another way beside the one given until now is to use unittest2 which is a back port of unittest's new features to Python 2.6, and you can make it work using the code above.

N.B: I'm a big fan of the new feature (SkipTest, test discovery, etc.) of unittest, so I intend to use unittest2 as much as I can. I advise to do the same, because there is a lot more than what unittest come with in Python 2.6 or lower.

Answer from mouad on Stack Overflow
🌐
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 - In this article, we’ve seen how to use Python unittest assertRaises method to write tests that verify that a certain code path is reached when an exception is raised. We’ve also seen how to use this method to verify the exception message and type. Keep in mind that the assertRaises method can only be used with exceptions that are raised in the with block. This means that you might need to explicitly call the function that raises the exception, as we saw in the examples above.
Discussions

unit testing - python unittest assertRaises - Stack Overflow
Some other modules like twisted provide assertRaises and though they try to maintain compatibility with python's unittest, your particular version of that module may be out of date. More on stackoverflow.com
🌐 stackoverflow.com
How do I assert exception raise in init?
assertRaises is a context handler, and should be used like: with self.assertRaises(...): ... code that should raise goes here More on reddit.com
🌐 r/learnpython
6
1
April 28, 2025
Unit test with exception
assertRaises can either take a callable or be used as a context manager. You could wrap filtags.handle... in a lambda, but it would be cleaner to use the context manager instead. def test_handle_file_with_nonexistent_filename(self): with self.assertRaises(FileNotFoundError): filetags.handle_file( os.path.join(self.tempdir, 'this filename does not exist - ' + self.testfilename, [...]))) More on reddit.com
🌐 r/learnpython
2
1
June 7, 2020
Python unittest an error-handling function
I am a great believer in TDD but I don't think it's worth unit-testing something so trivial. If I did want to test it, I'd pass in a mock Exception class. More on reddit.com
🌐 r/learnpython
12
1
September 10, 2023
🌐
Gitlab
ongspxm.gitlab.io › blog › 2016 › 11 › assertraises-testing-for-errors-in-unittest
assertRaises - testing for errors in unittest
November 16, 2016 - import unittest def func(): raise Exception('lets see if this works') class ExampleTest(unittest.TestCase): def test_error(self): self.assertRaises(Exception, lambda:func()) if __name__=='__main__': unittest.main() But lambda is a whole new monster on its own. It doesn't seem to be the right tool to use just as a wrapper for the function. This is a much more appropriate and pythonic way of using assertRaises.
🌐
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 ...
🌐
TutorialsPoint
tutorialspoint.com › unittest_framework › unittest_framework_exceptions_test.htm
UnitTest Framework - Exceptions Test
In the example below, a test function is defined to check whether ZeroDivisionError is raised. import unittest def div(a,b): return a/b class raiseTest(unittest.TestCase): def testraise(self): self.assertRaises(ZeroDivisionError, div, 1,0) if ...
🌐
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
The assertRaises method takes an exception type as its first argument, a function reference as its second, and an arbitrary number of arguments as the rest. In the code example, the assertRaises() test calls the raise_index_error() function.
🌐
Perez
daniel.perez.sh › blog › 2017 › unittest-assert-raises
assertRaises in Python - Daniel Perez
October 22, 2017 - This is pretty much it for how assertRaises works. Here is the full Python code for the explanations above · import unittest class SampleRaiseContextManager: def __init__(self, expected_exc, test_case): self.expected_exc = expected_exc self.test_case = test_case def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: self.test_case.fail("{0} was not raised".format(self.expected_exc)) elif isinstance(exc_value, self.expected_exc): return True return False class SampleTest(unittest.TestCase): def test_args_raise(self): self.argsAssertRaises(StopIterati
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › test-if-a-function-throws-an-exception-in-python
Test if a function throws an exception in Python - GeeksforGeeks
August 20, 2020 - Example 2 : Python3 · import unittest class MyTestCase(unittest.TestCase): # Returns false if 1 + 1 raises no Exception def test_1(self): with self.assertRaises(Exception): 1 + 1 if __name__ == '__main__': unittest.main() Output : F ====================================================================== FAIL: test_1 (__main__.MyTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/5bc65171e57a3294596f5333f4b7ed53.py", line 6, in test_1 1 + 1 AssertionError: Exception not raised ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) Since adding an integer to an integer (in this case 1 + 1) does not raise any exception, results in the unittest to fail.
🌐
Python Forum
python-forum.io › thread-21432.html
Unit testing - AssertRaises
Hi, I got this converter: def nmea_to_dd(coordinate, direction): if direction not in ['N', 'S', 'W', 'E']: raise TypeError('only N, S, E or W are valid directions') if coordinate.find('.') is 5: ''' longitude in the DDDMM.MM...
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › unittest.TestCase.assertRaises.html
unittest.TestCase.assertRaises — Python Standard Library
with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3)
🌐
CodingNomads
codingnomads.com › example-unit-test-python
Example Unit Test in Python
Python Documentation: unittest — Unit testing framework · Methods that inherit from unittest.TestCase()` are called test cases · The names for the test cases should all start with test_ assertEquals() confirms whether two values are equal to each other · assertRaises() confirms that a specific exception has been raised by your code ·
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python unittest
Introduction to Python unittest Framework
July 3, 2022 - The following example adds a test that expects a ValueError exception if the length is zero or negative: import unittest from square import Square class TestSquare(unittest.TestCase): def test_area(self): square = Square(10) area = square.area() self.assertEqual(area, 100) def test_length_with_wrong_type(self): with self.assertRaises(TypeError): square = Square('10') def test_length_with_zero_or_negative(self): with self.assertRaises(ValueError): square = Square(0) square = Square(-1)Copy
🌐
GeeksforGeeks
geeksforgeeks.org › python-exceptional-conditions-testing-in-unit-tests
Python | Exceptional Conditions Testing in Unit Tests - GeeksforGeeks
June 12, 2019 - Python3 1== import errno class TestIO(unittest.TestCase): def test_file_not_found(self): try: f = open('/file/not/found') except IOError as e: self.assertEqual(e.errno, errno.ENOENT) else: self.fail('IOError not raised') The 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 ·
🌐
Towards Data Science
towardsdatascience.com › home › data science › how to test if a function throws an exception in python
How To Test If a Function Throws An Exception in Python | Towards Data Science
October 11, 2022 - def test_greet_raises(self): with self.assertRaises(ValueError) as context : greet('bye') self.assertEqual('bye is not allowed', str(context.exception))
🌐
Peterbe.com
peterbe.com › plog › assertraises-and-inheritance
Careful with your assertRaises() and inheritance of exceptions - Peterbe.com
April 10, 2013 - import unittest class BadAssError(TypeError): pass def foo(): raise BadAssError("d'oh") class Test(unittest.TestCase): def test(self): self.assertRaises(BadAssError, foo) self.assertRaises(TypeError, foo) self.assertRaises(Exception, foo) if __name__ == '__main__': unittest.main() Basically, assertRaises doesn't just take the exception that is being raised and accepts it, it also takes any of the raised exceptions' parents. I've only tested it with Python 2.6 and 2.7.
🌐
ActiveState
code.activestate.com › recipes › 307970-a-better-assertraises-for-unittestpy
a better assertRaises() for unittest.py « Python recipes « ActiveState Code
The provided example TestCase.test_copy() tests Python's standard shutil.copy(). Run "test.py" once with each assertRaises/assertRaisesEx uncomment to see the improvements in error output and the added functionality of assertRaisesEx. To use in your own unittest TestCase classes, just copy the assertRaisesEx definition here into your own TestCase classes.
🌐
Real Python
realpython.com › python-unittest
Python's unittest: Writing Unit Tests for Your Code – Real Python
April 29, 2024 - For example, say that you want to code a function that takes a number from 0 to 2 and return the strings "rock", "paper", or "scissors". Instead of writing the function right away, you start writing the following tests: Language: Python Filename: ...