带有基类和子类的 Python 单元测试 [英] Python unit test with base and sub class
问题描述
我目前有几个单元测试,它们共享一组通用的测试.举个例子:
I currently have a few unit tests which share a common set of tests. Here's an example:
import unittest
class BaseTest(unittest.TestCase):
def testCommon(self):
print 'Calling BaseTest:testCommon'
value = 5
self.assertEquals(value, 5)
class SubTest1(BaseTest):
def testSub1(self):
print 'Calling SubTest1:testSub1'
sub = 3
self.assertEquals(sub, 3)
class SubTest2(BaseTest):
def testSub2(self):
print 'Calling SubTest2:testSub2'
sub = 4
self.assertEquals(sub, 4)
if __name__ == '__main__':
unittest.main()
上面的输出是:
Calling BaseTest:testCommon
.Calling BaseTest:testCommon
.Calling SubTest1:testSub1
.Calling BaseTest:testCommon
.Calling SubTest2:testSub2
.
----------------------------------------------------------------------
Ran 5 tests in 0.000s
OK
有没有办法重写上面的代码,这样第一个 testCommon
就不会被调用?
Is there a way to rewrite the above so that the very first testCommon
is not called?
我希望它只运行 4 个测试,而不是运行 5 个测试,其中 2 个来自 SubTest1,另外 2 个来自 SubTest2.似乎 Python unittest 正在自行运行原始 BaseTest,我需要一种机制来防止这种情况发生.
Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.
推荐答案
使用多重继承,这样你的具有通用测试的类本身不会从 TestCase 继承.
Use multiple inheritance, so your class with common tests doesn't itself inherit from TestCase.
import unittest
class CommonTests(object):
def testCommon(self):
print 'Calling BaseTest:testCommon'
value = 5
self.assertEquals(value, 5)
class SubTest1(unittest.TestCase, CommonTests):
def testSub1(self):
print 'Calling SubTest1:testSub1'
sub = 3
self.assertEquals(sub, 3)
class SubTest2(unittest.TestCase, CommonTests):
def testSub2(self):
print 'Calling SubTest2:testSub2'
sub = 4
self.assertEquals(sub, 4)
if __name__ == '__main__':
unittest.main()
这篇关于带有基类和子类的 Python 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!