Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

How does one write a unittest that fails only if a function doesn't throw an expected exception?

1 Answer

0 votes
by (106k points)
edited by

For writing a unit test to check whether a Python function throws an exception, you can use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module.


This function 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. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as an exception.

Following is an example regarding how we write unittest module:-

import mymod

class MyTestCase(unittest.TestCase): 

     def test1(self): 

         self.assertRaises(SomeCoolException, mymod.myfunc)

If you are looking for upskilling yourself in python you can join our Python Training and learn from the industry expert!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories