十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Python单元测试中有哪些装饰器?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Python单元测试unittest中提供了一下四种装饰器实现测试跳过和预期故障。
请查考Python手册中:
#以下装饰器实施测试跳过和预期故障:
@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()