Python unittest - setUpClass() is giving me trouble - why can't I inherit like this?

后端 未结 1 1841
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 18:24

I have unittest code like the following:

import unittest

class MyUnitTest(unittest.TestCase):
    def setUpClass(self):
        do_something_expensive_for_a         


        
1条回答
  •  长发绾君心
    2020-12-30 19:11

    setUpClass must be a class method. From the documentation:

    A class method called before tests in an individual class run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

    @classmethod
    def setUpClass(cls):
        ...
    

    See Class and Module Fixtures for more details.

    Your version is missing the @classmethod decorator:

    class MyUnitTest(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            do_something_expensive_for_all_sets_of_tests()
    
    class MyFirstSetOfTests(MyUnitTest):
        @classmethod
        def setUpClass(cls):
            super(MyFirstSetOfTests, cls).setUpClass()
            do_something_expensive_for_just_these_first_tests()
    

    The error is thrown because MyFirstSetOfTests.setUpClass() is called on the class, not on an instance, but you didn't mark your method as a classmethod and thus it was not passed in the automatic self argument. In the above updated code I used cls instead, to reflect that the name references the class object.

    0 讨论(0)
提交回复
热议问题