Home > Enterprise >  How do I assert that an exception will be raised when I run a function?
How do I assert that an exception will be raised when I run a function?

Time:10-24

I have been trying to create a test that asserts that an exception will be raised if I run it but for some reason it does not seem to work. Here is my code so far.

def f():
    return 1 '1'

def test():
    self.assertRaises(TypeError, f)

Thankful for any help!

CodePudding user response:

Why not raise the exception in the function itself? Your method will then look like:

def f():
    raise(TypeError)
    return 1   '1'

Another way would be to use assert to check if a function object is the same as the targte function:

assert raised_fcn==f, TypeError

CodePudding user response:

The function you're trying to use is TestCase.assertRaises. Since this is a method of the TestCase class, you need to have a TestCase instance, e.g.:

from unittest import TestCase

class MyTest(TestCase):
    def test(self):
        with self.assertRaises(TypeError):
            f()

The pytest utility will automatically run the test method in your TestCase class and print a report of whether it passed or failed, but you can also call it yourself as a normal function by doing something like:

if __name__ == '__main__':
    MyTest().test()

If you wanted to do this without unittest.TestCase you could use a simple try/except:

def test():
    try:
        f()
    except TypeError:
        pass
    else:
        raise AssertionError("Didn't raise TypeError!")

if __name__ == '__main__':
    test()
  • Related