待測源碼類:widget.pypython
#!/usr/bin/env python 框架
class Widget: 測試
def __init__(self, size = (40, 40)): ui
self._size = size spa
def getSize(self): .net
return self._size code
def resize(self, width, height): blog
if width == 0 or height < 0: ip
raise ValueError, "illegal size"
self._size = (width, height)
def dispose(self):
pass
測試代碼類:widget_unittest.py
#!/usr/bin/env python
import sys
import unittest
from widget import Widget
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testReSize(self):
self.widget.resize(20,30)
self.assertEqual(self.widget.getSize(), (20, 30))
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testReSize"))
return suite
if __name__ == "__main__":
unittest.TextTestRunner().run(suite())
# If you use IDE to execute test script in an external console,
# uncomment following code line.
# while True
# if raw_input("Type y or Y to close!") in ("y","Y"): sys.exit(0)
運行結果:python widget_unittest.py
[work@db-testing-com06-vm3.db01.baidu.com test]$ python widget_unittest.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
動態方法再也不覆蓋runTest()方法,而是爲測試類編寫多個測試方法(按習慣這些方法一般以test開頭),在建立TestCase子類的實例時必須給出測試方法的名稱,來爲PyUnit測試框架指明運行該測試用例時究竟應該調用測試類中的哪一個方法.
若是用於測試的類中全部的測試方法都以test開,Python程序員甚至能夠用PyUnit模塊提供的makeSuite()方法來構造一個TestSuite:
def suite():
return unittest.makeSuite(WidgetTestCase, "test")
原文連接:http://blog.csdn.net/sunboy_2050/article/details/5969842
標籤: Python