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()
好的,運行一下
ssFxu ====================================================================== FAIL: test_ce_3 (__main__.Test_ce) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Escplise\workspace\Pytest\src\test001\CE.py", line 20, in test_ce_3 self.assertTrue(self.a>16) AssertionError: False is not true ---------------------------------------------------------------------- Ran 5 tests in 0.000s 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單元測試_使用裝飾器實現測試跳過和預期故障的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
