Python标准测试框架unittest基础用法

import unittest
import sys
class TestStringMethod(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        print('test start')
        
    @classmethod
    def tearDownClass(self):
        print('test end')
        
    def setUp(self):
        print('single test start')
        
    def tearDown(self):
        print('single test end')
    
    @unittest.skipIf(condition = sys.platform == 'win32', reason = 'Do not support win32')
    def test_upper(self):
        print('upper')
        self.assertEqual('foo'.upper(), 'FOO')
        
    @unittest.skipIf(condition=sys.version_info < (3,8), reason='only support python 3.8 +')
    def test_isupper(self):
        print('isupper')
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper()) 
        
    def test_split(self):
        print('split')
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        #另一种重要的断言就是期待抛出指定类型的Error,
        #比如通过s.split(2)访问不存在的key时,断言会抛出TypeError:
        # 测试with里面的操作是不是成功地raise了我们想要的这个error(这里是TypeError)
        with self.assertRaises(TypeError):
            print('error type')
            s.split(2)

classmethod装饰器

setUpClass, setUpClass, setUp, setUp

unittest.skipIf装饰器

unittest.skipIf(condition = sys.platform == 'win32', reason = 'Do not support win32')

unittest库

unittest.TestCase类

测试文件的命名规范

测试模块,测试类,测试函数(方法)

测试代码的调用方式:

python -m test_string
只想调用某个测试方法怎么办

项目的目录结构,测试代码放哪里?

加__init__.py可以让文件变成module?

with self.assertRaises(TypeError)的含义:

测试with里面的操作(这里是s.split(2)语句)

是不是真的raise了我们想看到的这个error(这里是TypeError)

posted @   wjybq  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示