9

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

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

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()
4

1 回答 1

6

Python 的方法解析顺序导致了这种情况。使用您的继承结构,它按照您声明父类的顺序从左到右解析。

因此MyTest_DoesNotWork,python 将unittest.TestCase实现setUpand的实现tearDown,它什么都不做。因为unittest.TestCase.setUp没有写成合作并调用其他超类setUp方法,所以它只是停在那里并且没有打印任何内容。

使用MyTest_DoesWork,python 将改为MyClassTest1首先解析。就像unittest.TestCase,你还没有编写你的setUptearDown方法来协同调用超类方法。所以它停在那里,从不调用MyClassTest2方法。所以我猜想即使这实际上也没有像你预期的那样工作。更改您的MyClassTest1 setUptearDown方法以打印出“MyClassTest1”而不是,self.class您会看到它一直是被调用的那个。 MyClassTest2 setUp并且tearDown永远不会被调用。

于 2015-03-03T19:46:12.793 回答