【问题标题】:Python unittest inheritance setUp overridingPython unittest 继承 setUp 覆盖
【发布时间】:2017-09-30 23:49:37
【问题描述】:
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()

输出:

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)

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

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

    你可以试试这个代码:

    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):
            test = A()
            super(B, B).setUp(test)
    
        def test_two(self):
            self.assertNotEqual(5, 5)
    
    if __name__ == '__main__':
        unittest.main()
    

    以下是我对此类问题的一些启发:

    1. TypeError: attack() missing 1 required positional argument: 'self'

    2. super() and @staticmethod interaction

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我试过你的方法。它正在调用 A 的 setUp() 以及 B 的 setUp()。我只想使用 A 的 setUp()
      • 那么不要覆盖 B 中的 setUp。
      • 是的。谢谢。
      • 我的荣幸。很高兴它有帮助。
      • 我认为这个答案还有待改进。通过使用此解决方案,我们仍然可以进行 3 次测试。 test_one 在 A 和 B 中运行,然后在 B 中运行 test_two。有没有办法只使用另一个类的 setUp,所以我们只运行了两个测试?
      猜你喜欢
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 2010-10-19
      • 2012-09-27
      相关资源
      最近更新 更多