UnitTest 框架 – 跳过测试
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) 无条件跳过装饰测试。原因应该描述为什么要跳过测试。 |
| 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)