如何在Python中进行单元测试?

在Python中进行单元测试比较简单,可以分为以下四个步骤。 Python自带了单元测试的类:unittest — Unit testing framework,使用这个类可以满足绝大多数的日常开发需求。 一,新建测试类并继承unittest.TestCase

import unittest
class TestStringMethods(unittest.TestCase):

二,针对每个待测方法或每个待测功能模块编写一个测试方法

def test_upper(self):
    self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
    self.assertTrue('FOO'.isupper())
    self.assertFalse('Foo'.isupper())

def test_split(self):
    s = 'hello world'
    self.assertEqual(s.split(), \['hello', 'world'\])
    # check that s.split fails when the separator is not a string
    with self.assertRaises(TypeError):
        s.split(2)

三,在每个方法内部,使用unittest自带的“assert”方法对返回的结果或异常进行测试 如上面的例子所示,我们可以使用assertEqual,assertTrue,assertFalse来对测试结果进行断言,值得一提的是, with self.assertRaises(TypeError) 可以对被测方法的异常进行捕捉,只有不返回异常的测试才会被通过。 四,运行测试用例 运行测试用例有两种方法,第一种是在测试类所在的文件中加入如下代码,然后直接运行该脚本即可:

if __name__ == '__main__':
    unittest.main()

第二种是在命令行直接运行,

python -m unittest test_module1 test_module2         #运行两个模块
python -m unittest test_module.TestClass             #运行指定模块中的指定类
python -m unittest test_module.TestClass.test_method #运行指定模块中指定类的指定方法

可以看出第二种方法更加灵活。


如果你对本文有任何疑问或建议,欢迎联系我。本博客所有文章除特别声明外,均为原创文章,未经授权请勿转载!

fatal error LNK1112: 模块计算机类型“X86”与目标计算机类型“x64”冲突 上一篇
Windows下dll知识合集 下一篇

 目录