可以在unnitest框架中扩展setUpClass吗?

时间:2016-05-09 02:59:23

标签: python python-unittest

可以在unnitest框架中扩展setUpClass吗?

定义扩展unnitest.TestCase的Base1,Base1有setUpClass方法。

import unittest
class Base1(unittest.TestCase):

@classmethod
def setUpClass(cls):
    print('setupClass - this is Base1')

@classmethod
def tearDownClass(cls):
    print('tearDownClass - this is Base1')

定义扩展Base1类的Base2

from Base1 import Base1
import unittest

class Base2(Base1):

@classmethod
def setUpClass(cls):
    print('setupClass - this is Base2')

@classmethod
def tearDownClass(cls):
    print('tearDownClass - this is Base2')

def test_default_size(self):
    self.assertEqual('a','a')

def test_resize(self):
    self.assertEqual('a','b')

我希望Base1中的setUpClass和Base2中的setUpClass在Base2中的所有测试用例之前执行,这可能吗?

2 个答案:

答案 0 :(得分:2)

您必须明确呼叫setUpClasstearDownClass

class Base2(Base1):
    @classmethod
    def setUpClass(cls):
        print('setupClass - this is Base2')
        super(Base2, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        print('tearDownClass - this is Base2')
        super(Base2, cls).tearDownClass()

但是,如果您不添加这些类方法,则可以跳过定义它们:

class Base3(Base1):, 
    def test1(self):
        print('test1')

在这种情况下,来自setUpClass的{​​{1}}和tearDownClass将被隐式调用。

答案 1 :(得分:0)