也許這就是@Klaus的意思?
import unittest
class TestA(unittest.TestCase):
def setUp(self):
print "Setup # 1"
def test1(self):
print "Doing test1"
class TestB(unittest.TestCase):
def setUp(self):
print "Setup # 2"
def test2(self):
print "Doing test2"
if __name__ == "__main__":
unittest.main()
或者,您可以根據方法名稱更改設置。
雖然這可能是一個更難以維持的痛苦。
class TestA(unittest.TestCase):
def setUp(self):
if self._testMethodName == "test1":
print "Setup # 1"
elif self._testMethodName == "test2":
print "Setup # 2"
def test1(self):
print "Doing test1"
def test2(self):
print "Doing test2"
if __name__ == "__main__":
unittest.main()
都產生相同的輸出:
Output:
Setup # 1
Doing test1
.Setup # 2
Doing test2
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
編輯: 對不起,我不認爲我完全理解,但這裏是我實現您的評論的嘗試。 我的方法是重新應用BaseTest.setUp()
,而不是像你所描述的那樣儘量保持它完整。
TypeOneTests
和TypeTwoTests
繼承BaseTest
他們使用super(...)
class BaseTest(unittest.TestCase):
def setUp(self):
print "BaseTest setUp"
def tearDown(self):
print "BaseTest tearDown"
# you could add tests here but I didn't add any based on your comment
class TypeOneTests(BaseTest):
def setUp(self):
super(TypeOneTests, self).setUp()
print "TypeOneTests setUp"
def tearDown(self):
print "TypeOneTests tearDown"
def test(self):
print "a test in TypeOneTests"
class TypeTwoTests(BaseTest):
def setUp(self):
super(TypeTwoTests, self).setUp()
print "TypeTwoTests additional setUp"
def tearDown(self):
print "TypeTwoTests tearDown"
super(TypeTwoTests, self).tearDown()
def test(self):
print "a test in TypeTwoTests"
if __name__ == "__main__":
unittest.main()
輸出調用BaseTest
的裏面自己setUp
功能:
BaseTest setUp
TypeOneTests setUp
a test in TypeOneTests
TypeOneTests tearDown
.BaseTest setUp
TypeTwoTests additional setUp
a test in TypeTwoTests
TypeTwoTests tearDown
BaseTest tearDown
.
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
把它們在其他類。 –
你可以更具體一點,就像把另一類放到什麼地方一樣? – bwrabbit