Python自动单元测试实例

长平狐 发布于 2013/01/06 11:21
阅读 33
收藏 0

Python unittest模块的相关用法

 

待测源码类:widget.py

#!/usr/bin/env python

class Widget:
    def __init__(self, size = (40, 40)):
        self._size = size

    def getSize(self):
        return self._size

    def resize(self, width, height):
        if width == 0  or height < 0:
            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
加载中
返回顶部
顶部