說明一下,TestCase裡的setUp與tearDown是TestCase裡的每一個 test function 的pre-processing & post-processing,而setUpClass與tearDownClass是整個TestCase被run起來的pre-processing & post-processing。
以下的sample code,主要就是繼承TestSuite,定義一個自己的MyTestSuite,override run(),讓它試著去執行setUpClass與tearDownClass。
import unittest
import traceback
class MyTestSuite(unittest.TestSuite):
# sikuli jython 2.5 unittest doesn't have setUpClass & tearDownClass
# Add the class to support this feature
def __init__(self,*argv,**argd):
unittest.TestSuite.__init__(self, *argv, **argd)
def run(self, result):
sample = self._tests[0] if len(self._tests)>0 else None
if sample and hasattr(sample, 'setUpClass'):
try:
sample.setUpClass()
except:
traceback.print_exc()
for test in self._tests:
if result.shouldStop:
break
test(result)
if sample and hasattr(sample, 'tearDownClass'):
try:
sample.tearDownClass()
except:
traceback.print_exc()
return result
class MyTestCase(unittest.TestCase):
def setUpClass(self):
print 'MyTestCase::setUpClass'
def tearDownClass(self):
print 'MyTestCase::tearDownClass'
def test_MyTest1(self):
print 'MyTestCase::MyTest1'
def test_MyTest2(self):
print 'MyTestCase::MyTest2'
if __name__ == '__main__':
suites = unittest.TestSuite([unittest.makeSuite(MyTestCase, suiteClass=MyTestSuite)])
runner = unittest.TextTestRunner()
runner.run(suites)
# output result sequence ...
#>>> MyTestCase::setUpClass
#>>> MyTestCase::MyTest1
#>>> MyTestCase::MyTest2
#>>> MyTestCase::tearDownClass
沒有留言:
張貼留言