被跳过的用例 / 类 / 模块,与之相应的 setUp() / tearDown()、setUpClass / tearDownClass()、setUpModule() / tearDownModule() 也不会被执行。
6种跳过用例的方法
- 直接强制跳过
# reason 为说明跳过原因
@unittest.skip(reason)
实例
import unittest
class myTestCase(unittest.TestCase):
def test01(self):
print('test01')
@unittest.skip('跳过test02')
def test02(self):
print('test02')
def test03(self):
print('test03')
if __name__ == '__main__':
unittest.main()
执行结果
Ran 3 tests in 0.048s
OK (skipped=1)
Process finished with exit code 0
test01
Skipped: 跳过test02
test03
- 给定条件成立时跳过
# 条件condition为True时跳过
@unittest.skipIf(conidition, reason)
实例
import unittest
def odd(n):
if n % 2 == 1:
return True
return False
class myTestCase(unittest.TestCase):
def test01(self):
print('test01')
# 条件为True时跳过
@unittest.skipIf(odd(3), '跳过test02')
def test02(self):
print('test02')
def test03(self):
print('test03')
if __name__ == '__main__':
unittest.main()
执行结果
test01
Skipped: 跳过test02
test03
Ran 3 tests in 0.002s
OK (skipped=1)
Process finished with exit code 0
- 默认跳过,只有给定条件成立时才会执行(与 skipIf 相反)
# 条件condition为True时才会执行
@unittest.skipUnless(condition, reason)
实例
import unittest
def odd(n):
if n % 2 == 1:
return True
return False
class myTestCase(unittest.TestCase):
def test01(self):
print('test01')
# 条件为True时执行
@unittest.skipUnless(odd(2), '跳过test02')
def test02(self):
print('test02')
def test03(self):
print('test03')
if __name__ == '__main__':
unittest.main()
执行结果
test01
Skipped: 跳过test02
Ran 3 tests in 0.002s
OK (skipped=1)
test03
- 标记为预期失败/报错
# 如果执行时真的失败or报错,则会被认为测试通过Pass(因为符合预期)
# 如果执行成功了,则会被认为测试不通过Failure(不符合预期)
@unittest.expectedFailure
- TestCase类的方法
skipTest(reason)
实例
import unittest
class myTestCase(unittest.TestCase):
def test01(self):
print('test01')
def test02(self):
# 注意放在用例第一行
self.skipTest('跳过test02')
print('test02')
def test03(self):
print('test03')
if __name__ == '__main__':
unittest.main()
执行结果
test01
Skipped: 跳过test02
test03
Ran 3 tests in 0.003s
OK (skipped=1)
Process finished with exit code 0
- unittest异常类
# 引发此异常时,跳过
SkipTest(reason)
实例
import unittest
class myTestCase(unittest.TestCase):
def test01(self):
print('test01')
def test02(self):
try:
assert 3 % 2 == 0
print('test02')
except AssertionError:
raise unittest.SkipTest('跳过test02')
def test03(self):
print('test03')
if __name__ == '__main__':
unittest.main()
执行结果
Ran 3 tests in 0.002s
OK (skipped=1)
test01
Skipped: 跳过test02
test03
Process finished with exit code 0