python unittest模块

一个类,继承了unittest.TestCase方法,就是一个测试用例。

一个测试用例test case可以包含许多测试方法test methodsetup()tearDown()是针对 测试方法 执行前后的测试环境(test fixture) 的搭建和还原。setupClass,tearDownClass是对 test case 执行前后的测试环境的搭建和还原。测试套装TsetSuite可以通过加载器TestLoader从许多模块、许多测试用例中加载测试用例,然后通过TextTestRunner来执行suite中的测试用例。(Testsuite可以嵌套Testsuite)

实例:

要测试的类

mathfunc.py

def add(a, b):
    return a+b

def minus(a, b):
    return a-b

def multi(a, b):
    return a*b

def divide(a, b):
    return a/b

测试类

test_mathfunc.py

# -*- coding: utf-8 -*-
import unittest
from mathfunc import *


class TestMathFunc(unittest.TestCase):  # 继承unittest.TestCase,是一个用例
    """Test mathfuc.py"""
# 测试环境搭建,每个 test 开头的测试方法 之前都会执行一遍
    def setUp(self):
        print("do something before test.Prepare environment.")
# 测试环境还原,每个 test 开头的测试方法 之后都会执行一遍
    def tearDown(self):
        print("do something after test.Clean up.")

# 环境搭建,在 测试用例 执行前执行一次
    @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_add(self):              # test 开头的,是测试方法
        """Test method add(a, b)"""
        self.assertEqual(3, add(1, 2))
        self.assertNotEqual(3, add(2, 2))

    @unittest.skip("I don't want to run this case.")  # 跳过某条case
    def test_minus(self):
        """Test method minus(a, b)"""
        self.assertEqual(1, minus(3, 2))

    def test_multi(self):
        self.skipTest('Do not run this.')   # 也可以用这种方法跳过case
        """Test method multi(a, b)"""
        self.assertEqual(6, multi(2, 3))

    def test_divide(self):
        """Test method divide(a, b)"""
        self.assertEqual(2, divide(6, 3))
        self.assertEqual(2.5, divide(5, 2))


if __name__ == '__main__':
    unittest.main(verbosity=2)   # verbosity 报告的详细程度,默认1
    # unittest.main()

测试Suite

test_suite.py

# -*- coding: utf-8 -*-

import unittest
from test_mathfunc import TestMathFunc
from HTMLTestRunner import HTMLTestRunner

if __name__ == '__main__':
    suite = unittest.TestSuite()

# 添加 case 的几种方式
    tests = [TestMathFunc("test_add"), TestMathFunc("test_minus"), TestMathFunc("test_divide")]
    suite.addTests(tests)

    # 1 直接用addTest方法添加单个TestCase,有序
    suite.addTest(TestMathFunc("test_multi"))

    # 2 用addTests + TestLoader,可能不按照顺序执行
    # loadTestsFromName(),传入'模块名.TestCase名'
    suite.addTests(unittest.TestLoader().loadTestsFromName('test_mathfunc.TestMathFunc'))
    suite.addTests(unittest.TestLoader().loadTestsFromNames(['test_mathfunc.TestMathFunc']))  # loadTestsFromNames(),类似,传入列表

    # 3 loadTestsFromTestCase(),传入TestCase
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestMathFunc))


# 1. 使用 HTMLTestRunner 将执行结果写入 html 文件,需要导入 HTMLTestRunner.py
    # with open('HTMLReport.html', 'w') as f:
    #     runner = HTMLTestRunner(stream=f,
    #                             title='MathFunc Test Report',
    #                             description='generated by HTMLTestRunner.',
    #                             verbosity=2
    #                             )
    #     runner.run(suite)

# 2. 将执行结果写入文件
#     with open('UnittestTextReport.txt', 'a') as f:
#         runner = unittest.TextTestRunner(stream=f, verbosity=2)
#         runner.run(suite)

# 3. 执行结果打印在控制台
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

HTMLTestRunner.py地址:https://files.cnblogs.com/files/wztshine/HTMLTestRunner.zip

原文链接:https://blog.csdn.net/songlh1234/article/details/101202938?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

更详细的教程:
https://www.cnblogs.com/wztshine/p/14000280.html

posted @ 2020-06-16 15:01  wztshine  阅读(147)  评论(0编辑  收藏  举报