Python unittest继承setUp覆盖

won*_*der 3 python python-unittest

import unittest

class A(unittest.TestCase):
    def setUp(self):
        print "Hi it's you",self._testMethodName

    def test_one(self):
        self.assertEqual(5,5)

    def tearDown(self):
        print "Bye it's you", self._testMethodName

class B(A,unittest.TestCase): 

    def setUp(self):
        print "Hi it's me", self._testMethodName

    def test_two(self):
        self.assertNotEqual(5,5)


unittest.main()
Run Code Online (Sandbox Code Playgroud)

输出 :

Hi it's you test_one
Bye it's you test_one
.Hi it's me test_one
Bye it's you test_one
.Hi it's me test_two
FBye it's you test_two

======================================================================
FAIL: test_two (__main__.B)
----------------------------------------------------------------------

Traceback (most recent call last):
  File "try_test_generators.py", line 19, in test_two
    self.assertNotEqual(5,5)
AssertionError: 5 == 5

----------------------------------------------------------------------
Ran 3 tests in 0.005s

FAILED (failures=1)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,测试用例test_one使用setUp()类 A 的 。但是在派生类test_one中使用setUp()类 B 的 。有没有办法可以setUp()为从它派生的每个测试用例使用A 的方法?

hsp*_*her 6

只要确保在您覆盖它的每个子类中调用 super 即可。

class B(A, unittest.TestCase):

    def setUp(self):
        print "Hi it's me", self._testMethodName
        super(B, self).setUp()
Run Code Online (Sandbox Code Playgroud)