Python单元测试框架unittest
- 在unittest.main()中加 verbosity 参数可以控制输出的错误报告的详细程度,默认是 1,如果设为 0,则不输出每一用例的执行结果,如果设为 2,则输出详细的执行结果;
- 测试用例忽略
@unittest,skip(reason):无条件跳过
@unittest.skipIf(condition, reason):当condition为True时跳过
@unittest.skipUnless(condition, reason):当condition为False时跳过
- 控制用例的执行顺序
方法1: 通过TestSuite按照顺序添加想要执行的方法
suite = unittest.TestSuite() testcases = [TestClass('method_c'), TestClass('method_b'),TestClass('method_a')] suite.addTests(testcases) unittest.TextTestRunner(verbosity=2).run(suite)
方法2:顺应testunit的执行顺序,就是通过控制方法名字来实现
test_a_casename test_b_casename test_c_casename
- 将结果输出到文件中
suite = unittest.TestSuite() testcases = [TestClass('method_c'), TestClass('method_b'),TestClass('method_a')] suite.addTests(testcases) with open('report.txt', 'a') as f: runner = unittest.TextTestRunner(stream=f, verbosity=2) runner.run(suite)
执行此文件,可以看到,在同目录下生成了report.txt
- setUp和tearDown在每次执行case前后都执行了一次
如果想要在所有case执行之前准备一次环境,并在所有case执行结束之后再清理环境,我们可以用 setUpClass() 与
tearDownClass():
import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): print "This setUpClass() method only called once." @classmethod def tearDownClass(cls): print "This tearDownClass() method only called once too." def test_a(self): print 'aaaaaaaaaaa' def test_b(self): print 'bbbbbbbbbb' if __name__ == '__main__': unittest.main()
运行结果:
This setUpClass() method only called once. aaaaaaaaaaa .bbbbbbbbbb .This tearDownClass() method only called once too. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
- 生成html报告
我们下载HTMLTestRunner.py,并放到当前目录下,或者你的 Python的Lib目录下,就可以导入运行了。
下载地址:
灰蓝修改版:HTMLTestRunner.py(已调整格式,中文显示) https://pan.baidu.com/s/1b0eD41ml8fMdTO7nsBBcjA
with open('report.html', 'w') as f: runner =HTMLTestRunner(stream=f, title='demotest',description= 'htmlrunner', verbosity=2) runner.run(suite)
日行一善, 日写一撰