关于单元测试:python多重继承单元测试

Python multiple inheritance unittest -

我试图理解使用unittest.TestCase类进行多重继承时会发生什么。

MyTest_DoesWork输出我所期望的,这是setUp()tearDown()都被触发。这不是发生在MyTest_DoesNotWork上。为什么会这样?有什么线索吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import unittest

class MyClassTest1(object):
    def setUp(self):
        print 'Setting up', self.__class__
    def test_a1(self):
        print"Running test_a1 for class", self.__class__
    def test_a2(self):
        print"Running test_a2 for class", self.__class__
    def tearDown(self):
        print 'Tearing down', self.__class__

class MyClassTest2(object):
    def setUp(self):
        print 'Setting up', self.__class__
    def test_b1(self):
        print"Running test_b1 for class", self.__class__
    def test_b2(self):
        print"Running test_b2 for class", self.__class__
    def tearDown(self):
        print 'Tearing down', self.__class__

class MyTest_DoesNotWork(unittest.TestCase, MyClassTest1, MyClassTest2):
   """
    Output:
    Running test_a1 for class <class '__main__.MyTest_DoesNotWork'>
    .Running test_a2 for class <class '__main__.MyTest_DoesNotWork'>
    .Running test_b1 for class <class '__main__.MyTest_DoesNotWork'>
    .Running test_b2 for class <class '__main__.MyTest_DoesNotWork'>
   """

    pass

class MyTest_DoesWork(MyClassTest1, MyClassTest2, unittest.TestCase):
   """
    Output:
    Setting up <class '__main__.MyTest_DoesWork'>
    Running test_a1 for class <class '__main__.MyTest_DoesWork'>
    Tearing down <class '__main__.MyTest_DoesWork'>
    .Setting up <class '__main__.MyTest_DoesWork'>
    Running test_a2 for class <class '__main__.MyTest_DoesWork'>
    Tearing down <class '__main__.MyTest_DoesWork'>
    .Setting up <class '__main__.MyTest_DoesWork'>
    Running test_b1 for class <class '__main__.MyTest_DoesWork'>
    Tearing down <class '__main__.MyTest_DoesWork'>
    .Setting up <class '__main__.MyTest_DoesWork'>
    Running test_b2 for class <class '__main__.MyTest_DoesWork'>
    Tearing down <class '__main__.MyTest_DoesWork'>
   """

    pass

if __name__ =="__main__":
    unittest.main()


python的方法解析顺序导致了这一点。对于继承结构,它按照您声明父类的顺序从左到右进行解析。

因此,使用MyTest_DoesNotWork,python将攻击setUptearDownunittest.TestCase实现,它们不起任何作用。因为unittest.TestCase.setUp不是为了合作而写的,它调用了其他的超类setUp方法,所以它就停在那里,不打印任何内容。

使用MyTest_DoesWork,python将首先解析为MyClassTest1。就像unittest.TestCase一样,您没有编写setUptearDown方法来协作调用超类方法。所以它停在那里,从不调用MyClassTest2方法。所以我猜即使这样也不会像你预期的那样奏效。把你的MyClassTest1setUptearDown方法改成打印"myClassTest1"而不是self.class的方法,你会发现它一直被调用。不叫MyClassTest2setUptearDown