• 【自动化测试】unitest


    • 概念

        基于断言机制来判断输入参数后函数的输出与期望结果的是否一致。

    • unitest.TestCase中内置的assertXxxx方法
    序号断言方法断言描述
    1 assertEqual(arg1, arg2, msg=None) 验证arg1=arg2,不等则fail
    2 assertNotEqual(arg1, arg2, msg=None) 验证arg1 != arg2, 相等则fail
    3 assertTrue(expr, msg=None) 验证expr是true,如果为false,则fail
    4 assertFalse(expr,msg=None) 验证expr是false,如果为true,则fail
    5 assertIs(arg1, arg2, msg=None) 验证arg1、arg2是同一个对象,不是则fail
    6 assertIsNot(arg1, arg2, msg=None) 验证arg1、arg2不是同一个对象,是则fail
    7 assertIsNone(expr, msg=None) 验证expr是None,不是则fail
    8 assertIsNotNone(expr, msg=None) 验证expr不是None,是则fail
    9 assertIn(arg1, arg2, msg=None) 验证arg1是arg2的子串,不是则fail
    10 assertNotIn(arg1, arg2, msg=None) 验证arg1不是arg2的子串,是则fail
    11 assertIsInstance(obj, cls, msg=None) 判断一个变量是否是某个类型
    12 assertNotIsInstance(obj, cls, msg=None) 判断一个变量是否不是某个类型
    • 运行测试

      增加如下代码,可以运行当前源文件中的所有测试用例。

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

      也可以使用

    python -m unitest 测试文件

    如果没有指定测试用例,该命令将自动查找该目录下的所有测试用例并进行运行。

    • 使用测试包(TestSuite)

    使用测试包可以将多个测试用例组织起来,使用测试运行器(TestRunner)来运行该测试包中所含的所有测试用例。

    import unitest
    from PythonTest.python_unittest import TestFkMath
    from PythonTest.test_hello import TestHello
    
    test_cases = (TestHello, TestFkMath)
    
    def whole_suite():
        # 创建测试加载器
        loader = unittest.TestLoader()
    
        # 创建测试包
        suite = unittest.TestSuite()
    
        # 遍历所有测试类
        for test_class in test_cases:
            # 从测试类中加载测试用例
            tests = loader.loadTestsFromTestCase(test_class)
            # 将测试用例添加到测试包中
            suite.addTests(tests)
        return suite
    
    
    if __name__ == "__main__":
        with open('test_report.txt', 'a') as f:
            # 创建测试运行器(TestRunner),并将测试报告输出到文件中
            runner = unittest.TextTestRunner(verbosity=2, stream=f)
            runner.run(whole_suite())
    • 测试固件

      setUp() 用于初始化测试固件

      tearDown() 用于销毁测试固件

    • 跳过测试用例,两种方式

      (1)使用skipXxx装饰器跳过测试用例。@unittest.skip(reason),@unittest.skipIf(condition, reason),@unittest.skipUnless(condition,reason)

      (2)使用skipTest()方法跳过

    self.skipTest('临时跳过test_add')
  • 相关阅读:
    对pg_latch.c 的来源探索
    对PostgreSQL的执行计划的初步学习
    21个css和Ajax表格
    23种设计模式有趣诠释
    Spket IDE, Ext开发人员的紫色匕首~
    Sql Server 2008 Reporting Services系列(一)
    C#积累(二)——ASP.NET的Session会加锁
    在TSQL语句中访问远程数据库(openrowset/opendatasource/openquery)
    ASP.NET视图的保存与加载解析(一)——视图的保存
    C#积累(一)——扩展方法就近原则和匿名类型的成员探讨
  • 原文地址:https://www.cnblogs.com/amberwang2018/p/14856324.html
Copyright © 2020-2023  润新知