Python单元测试unittest中提供了一下四种装饰器实现测试跳过和预期故障。(使用Python 2.7.13)
请查考Python手册中:
https://docs.python.org/dev/library/unittest.html
The following decorators implement test skipping and expected failures:
#以下装饰器实施测试跳过和预期故障:
@unittest.skip(原因)
Unconditionally skip the decorated test. reason should describe why the test is being skipped.
#无条件跳过装饰测试。 原因应该说明为什么要跳过测试。
@unittest.skipIf(条件,原因)
Skip the decorated test if condition is true.
#如果条件为真,跳过装饰测试。
@unittest.skipUnless(条件,原因)
Skip the decorated test unless condition is true.
# 跳过装饰的测试,除非条件是真的。
@unittest.expectedFailure
Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure.
#将测试标记为预期的失败。 如果测试在运行时失败,则测试不会被视为失败。
(以上采用谷歌翻译,可能会有差异)
好了,写段代码看下,test.py ,使用的Eclipse
#coding:UTF-8
import unittest
from test.test_pprint import uni
class Test_ce(unittest.TestCase):
a=16
b=10
@unittest.skip('无条件跳过')
def test_ce1(self):
self.assertEqual((self.a-self.b), 16)
#判断是否相等
@unittest.skipIf(True==1, '条件为真则跳过')
def test_ce_2(self):
self.assertFalse(self.a==self.b)
#判断是否为False
@unittest.skipUnless(1==1, '条件为假则跳过')
def test_ce_3(self):
self.assertTrue(self.a>16)
#判断是否为True
@unittest.expectedFailure
def test_ce_4(self):
self.assertFalse(self.a==16)
@unittest.expectedFailure
def test_ce_5(self):
self.assertFalse(self.a==15)
if __name__ == '__main__':
unittest.main()
好的,运行一下
1 ssFxu
2 ======================================================================
3 FAIL: test_ce_3 (__main__.Test_ce)
4 ----------------------------------------------------------------------
5 Traceback (most recent call last):
6 File "D:EscpliseworkspacePytestsrc est001CE.py", line 20, in test_ce_3
7 self.assertTrue(self.a>16)
8 AssertionError: False is not true
9
10 ----------------------------------------------------------------------
11 Ran 5 tests in 0.000s
12
13 FAILED (failures=1, skipped=2, expected failures=1, unexpected successes=1)
好的,我们对第1行代码进行分析:
s:全称是skipped(跳过)
s:条件为真,所以也是skipped(跳过)
F:条件为真,所以忽略装饰器,执行断言代码,显然是failures(失败)
x:断言结果显然是失败的,但是这是在我们意料之中,所以是expected failures(预期的失败)
u:断言结果显然是pass,但是我们预计可能不通过,所以是unexpected successes(意想不到的成功)
即第13行代码 所示 FAILED (failures=1, skipped=2, expected failures=1, unexpected successes=1)
Python单元测试——使用装饰器实现测试跳过和预期故障
发表于:2017-08-06
作者:搬砖学徒
来源:
 相关文章
Python单元测试之道:从入门到精通 Python测试 | 在python中创建单元测试 如何使用Python进行单元测试 Python单元测试——深入理解unittest python unittest之加载及跳过测试方法和示例 Python使用装饰器在执行单元测试时配置环境- 周排行
- 月排行
- 评论排行
-   Android开发中如何进行单元测试?
-   单元测试:优雅的Spock框架
-   iOS网络接口的单元测试
-   对Controller的单元测试
-   单元测试运行原理探究
-   单元测试实践总结
-   单元测试和集成测试业务应用程序
-   Python单元测试之道:从入门到精通
-   Android开发中如何进行单元测试?
-   简化Java单元测试数据
-   什么是单元测试,和集成测试有什么区别?
-   一次单元测试优化的过程总结
-   黑盒测试方法之组合覆盖法
-   使用Elixir来优化Erlang的单元测试用例
-   从软件出发,非功能测试思考总结
-   展望2017,谁是网络技术头牌?
-   C/C++单元测试工具Visual Unit 4 介绍
-   国内外最好用的6款Bug跟踪管理系统
-   性能测试指标评估必读
-   百度软件测试方案模板
-   38张史上最全的IT工程师技能图谱
-   C/C++单元测试工具Visual Unit 4 介绍
-   2019年,你会选哪些安全测试工具?
-   十款Web服务器性能压力测试工具
-   软件测试入门指南:周期、模型和文档化
-   记自动化测试成神学习之路
-   软件测试全景图 -最全的思维导图