老李分享:走读unittest源码

      poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标。poptest测试开发工程师就业培训感兴趣,请大家咨询qq:908821478,最近学员的就业推荐开始,帮助学员梳理学习的知识点,其中涉及到我们在学习中的单元测试框架unittest,在下面和大家分享下里面涉及到的内容,以及源码情况。

一,用法

unittest模块的用法很简单,定义个 TestCase的子类,然后根据需要重载Setup()和TearDown()两个方法。并且在类中定义一些测试用例条目的“方法” ,以test开头命名即可

import laoli

import unittest

class ProductTestCase(unittest.TestCase):

    def setUp(self):

        print 'units test begin'+'#'*20

    def tearDown(self):

        print 'unittest end'+'#'*20

    def testxx(self):

        print 'this is just test'

    def testIntegerProduct(self):

        for x in xrange(-10,10):

            for y in xrange(-10,10):

                p = kk.product(x,y)

                self.failUnless(p == x*y,'integer multiplication failture')

    def testFractalProduct(self):

        for x in xrange(-10,10):

            for y in xrange(-10,10):

                x = x/10.0

                y = y/10.0

                p = kk.product(x,y)

                self.failUnless(p == x*y,'fractal multiplication failture')

 

if __name__ == '__main__':

unittest.main()

 

其中laoli为被测模块

注意到代码中的testIntegerProduct(self) 及 testFractalProduct(self) 两个以test开头命名的方法即是测试用例条目,整个类为TestCase的子类,unittest通过这两个信息(红色标注部分)来识别测试用例和用例下的条目。

通过调用unitest.main()方法来启动单元测试。