UnitTest 框架 - 跳过测试
自 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"表示已跳过测试。
跳过测试的替代语法是在测试函数内使用实例方法 skipTest()。
def testadd2(self):
self.skipTest("another method for skipping")
self.assertTrue(add(4 + 5) == 10)
以下装饰器实现测试跳过和预期失败 −
| S.No. | 方法与说明 |
|---|---|
| 1 | unittest.skip(reason) 无条件跳过装饰的测试。 reason 应描述跳过测试的原因。 |
| 2 | unittest.skipIf(condition,reason) 如果条件为真,则跳过修饰测试。 |
| 3 | unittest.skipUnless(condition,reason) 除非条件为真,否则跳过修饰测试。 |
| 4 | unittest.expectedFailure() 标记测试被视为预期失败。如果测试在运行时失败,则测试不被视为失败。 |
以下示例演示了条件跳过和预期失败的使用。
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)

