Python unittest模組的相關用法
待測源碼類:widget.py
#!/usr/bin/env python</p><p>class Widget:<br /> def __init__(self, size = (40, 40)):<br /> self._size = size</p><p> def getSize(self):<br /> return self._size</p><p> def resize(self, width, height):<br /> if width == 0 or height < 0:<br /> raise ValueError, "illegal size"<br /> self._size = (width, height)</p><p> def dispose(self):<br /> pass
測試代碼類:widget_unittest.py
#!/usr/bin/env python</p><p>import sys<br />import unittest<br />from widget import Widget</p><p>class WidgetTestCase(unittest.TestCase):<br /> def setUp(self):<br /> self.widget = Widget() </p><p> def tearDown(self):<br /> self.widget = None</p><p> def testSize(self):<br /> self.assertEqual(self.widget.getSize(), (40, 40))</p><p> def testReSize(self):<br /> self.widget.resize(20,30)<br /> self.assertEqual(self.widget.getSize(), (20, 30))</p><p>def suite():<br /> suite = unittest.TestSuite()<br /> suite.addTest(WidgetTestCase("testSize"))<br /> suite.addTest(WidgetTestCase("testReSize"))<br /> return suite</p><p>if __name__ == "__main__":<br /> unittest.TextTestRunner().run(suite())<br /> # If you use IDE to execute test script in an external console,<br /> # uncomment following code line.<br /> # while True<br /> # 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")