[Python] Correct usage of assertRaises in Python unit tests

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to figure out how to correctly use assertRaises() of the Python unittest module. I have a ValueError in my function that gets raised. However, when testing in my unit tests, I'm getting mixed results with two different ways of using assertRaises().

    When I write the test like this, it works:

    import unittest

    class MyTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
    pass

    def test_error(self):
    with self.assertRaises(ValueError):
    func(a)


    However, if I write my test like below, it does not work even though the ValueError gets raised:

    def test_error(self):
    self.assertRaises(ValueError, func(a))


    Why would one way work and not the other?

    Continue reading...

Compartilhe esta Página