PyUint

官方文档:https://docs.python.org/2/library/unittest.html#test-discovery

PyUnit,python官方提供的单元测试框架。提供test case自动发现、运行、结果汇聚展示功能。

1、定义test case,主要有以下4步:
(1)继承 unittest.TestCase,定义测试类
(2)每个test case定义为一个function,function 名字以’test‘开头,除self外不能有其他参数,不能有返回值
(3)通过 unittest.TestCase 提供的各类assert 语句判断case成功或失败。TestCase提供的断言类型非常非常多,应用总要多加留意,使用最合适的。
(4)如果需要可以定义setUp(self),tearDown(self)方法,完成测试准备和测试环境清理。setUp,tearDown为每个test case执行一次。
(unittest.TestCase:重要的基类,提供run,setUp(可在子类覆写)等方法;提供各种断言,使用TestCase提供的断言,可以使PyUnit统计哪些case成功、哪些case失败,用于最后展示。)

class MyTestClass(unittest.TestCase):
    def setUp(self):
        print 'setUp func'

    def tearDown(self):
        print 'tearDown func'

    def test_8_1(self):
        self.assertEquals(1, 1)

    def test_8_2(self):
        self.assertNotEqual(0, 1)

2、test case 发现
命令行执行:python -m unittest discover,当前目录及其子目录所有文件名以“test/Test”开头的文件中的测试用例都会被执行(子目录必须有__init__.py文件)。

discover子命令,还支持 -p -s -t 参数,-p指定从文件名符合哪些pattern的文件中搜索测试用例。详见官方文档。

3、skip test case / test class
PyUnit 提供如下三种装饰器用来跳过test case,这些装饰器装饰class时,用来跳过整个test class。

  • unittest.skip(reason) # reason 为字符串,一般用来说明跳过case的原因
  • unittest.skipIf(condition,reason)
  • unittest.skipUnless(condition, reason)

也可以自定义skip装饰器,详见官方文档

class MyTestTwo(unittest.TestCase):
    @unittest.skipIf(2>1, 'just for test')
    def test_2_1(self):
        self.assertEquals(1, 1)

4、unittest.expectedFailure()
被expectedFailure 装饰的case,如果运行失败,不会算作失败。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值