0 votes
in Python by
Explain about Catching Exceptions?

1 Answer

0 votes
by
Another important assertion, assertRaises is used to catch exceptions.

assertRaises tries to check if a specified Exception is raised, when the test runs.

The test passes, if the specified exception is raised or else it fails.

The below shown test test_sample1 written in another module test_module2.py catches TypeError raised while adding an integer and a string.

from proj.sample_module import add2num

import unittest

class SampleTestClass(unittest.TestCase):

    def test_sample1(self):

        self.assertRaises(TypeError, add2num, 3, 'hello')

Running the above test with below command, passes the test.

python -m unittest test.test_module2

You can also use with for catching exceptions.

The previous example can be written as shown below.

from proj.sample_module import add2num

import unittest

class SampleTestClass(unittest.TestCase):

    def test_sample1(self):

        with self.assertRaises(TypeError) as e:

            r = add2num(3, 'hello')

        self.assertEqual(str(e.exception), "unsupported operand type(s) for +: 'int' and 'str'")

The example also validates the error message, which is displayed.

Related questions

0 votes
asked Feb 11, 2020 in Python by rahuljain1
0 votes
asked Jan 11, 2021 in Python by SakshiSharma
...