首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python继承setUp重写

Python继承setUp重写
EN

Stack Overflow用户
提问于 2017-05-03 08:36:26
回答 2查看 5.1K关注 0票数 6
代码语言:javascript
运行
复制
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()

输出:

代码语言:javascript
运行
复制
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()吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-03 09:25:30

只需确保在您重写过的每个子类中调用超级。

代码语言:javascript
运行
复制
class B(A, unittest.TestCase):

    def setUp(self):
        print "Hi it's me", self._testMethodName
        super(B, self).setUp()
票数 9
EN

Stack Overflow用户

发布于 2017-05-03 09:23:32

您可以尝试以下代码:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43755092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档