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()
来获取每个测试用例?
答案 0 :(得分:3)
请确保在您已覆盖的所有儿童班级中打电话给超级。
class B(A, unittest.TestCase):
def setUp(self):
print "Hi it's me", self._testMethodName
super(B, self).setUp()
答案 1 :(得分:0)
您可以尝试以下代码:
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()
以下是我对这类问题的一些启发: