📅  最后修改于: 2020-12-03 05:28:48             🧑  作者: Mango
自Python 2.7起增加了对跳过测试的支持。可以有条件地或无条件地跳过单个测试方法或TestCase类。该框架允许将某个测试标记为“预期失败”。该测试将“失败”,但在TestResult中不会被视为失败。
要无条件地跳过方法,可以使用以下unittest.skip()类方法-
import unittest
def add(x,y):
return x+y
class SimpleTest(unittest.TestCase):
@unittest.skip("demonstrating skipping")
def testadd1(self):
self.assertEquals(add(4,5),9)
if __name__ == '__main__':
unittest.main()
由于skip()是一个类方法,因此以@标记为前缀。该方法有一个参数:描述跳过原因的日志消息。
执行以上脚本后,控制台上将显示以下结果:
C:\Python27>python skiptest.py
s
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK (skipped = 1)
字符“ s”表示已跳过测试。
跳过测试的替代语法是在test函数内部使用实例方法skipTest()。
def testadd2(self):
self.skipTest("another method for skipping")
self.assertTrue(add(4 + 5) == 10)
以下装饰器实现测试跳过和预期的失败-
S.No. | Method & Description |
---|---|
1 |
unittest.skip(reason) Unconditionally skip the decorated test. reason should describe why the test is being skipped. |
2 |
unittest.skipIf(condition, reason) Skip the decorated test if condition is true. |
3 |
unittest.skipUnless(condition, reason) Skip the decorated test unless condition is true. |
4 |
unittest.expectedFailure() Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure. |
以下示例演示了条件跳过和预期失败的用法。
import unittest
class suiteTest(unittest.TestCase):
a = 50
b = 40
def testadd(self):
"""Add"""
result = self.a+self.b
self.assertEqual(result,100)
@unittest.skipIf(a>b, "Skip over this routine")
def testsub(self):
"""sub"""
result = self.a-self.b
self.assertTrue(result == -10)
@unittest.skipUnless(b == 0, "Skip over this routine")
def testdiv(self):
"""div"""
result = self.a/self.b
self.assertTrue(result == 1)
@unittest.expectedFailure
def testmul(self):
"""mul"""
result = self.a*self.b
self.assertEqual(result == 0)
if __name__ == '__main__':
unittest.main()
在上面的示例中,将跳过testsub()和testdiv()。在第一种情况下,a> b为真,而在第二种情况下,b == 0不为真。另一方面,testmul()已被标记为预期失败。
运行上面的脚本时,两个跳过的测试显示“ s”,并且预期的失败显示为“ x”。
C:\Python27>python skiptest.py
Fsxs
================================================================
FAIL: testadd (__main__.suiteTest)
Add
----------------------------------------------------------------------
Traceback (most recent call last):
File "skiptest.py", line 9, in testadd
self.assertEqual(result,100)
AssertionError: 90 != 100
----------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (failures = 1, skipped = 2, expected failures = 1)