python unittest学习4---跳过测试与预计的失败

当需要跳过某个测试用例或者某个测试类或者预期失败的测试用例,可以使用如下方法,这样就不会导致测试报告结果的失败

import unittest
import sys

class TestStringMethods(unittest.TestCase):
    @unittest.skipUnless(sys.platform.startswith("os"), "requires Windows")
    def test_upper(self):
        self.assertEqual("foo".upper(), "FOO")
    @unittest.skip("showing class skipping")
    def test_isupper(self):
        self.assertTrue("FOO".isupper())
        self.assertFalse("Foo".isupper())
    def test_split(self):
        s="hello world"
        self.assertEqual(s.split(),["hello","world"])

if __name__=="__main__":
unittest.main()

此时运行的结果为:

s.s
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK (skipped=2)

同样也可以跳过某个测试类:如下:

import unittest
@unittest.skip("showing class skipping")
class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual("foo".upper(), "FOO")
    def test_isupper(self):
        self.assertTrue("FOO".isupper())
        self.assertFalse("Foo".isupper())
    def test_split(self):
        s="hello world"
        self.assertEqual(s.split(),["hello","world"])

if __name__=="__main__":
unittest.main()

运行的结果为:

sss
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK (skipped=3)

备注:

@ unittest. skip (reason)
跳过被此装饰器装饰的测试。  reason 为测试被跳过的原因。
@ unittest. skipIf (conditionreason)
当  condition 为真时,跳过被装饰的测试。
@ unittest. skipUnless (conditionreason)
跳过被装饰的测试,除非  condition 为真。
@ unittest. expectedFailure
把测试标记为预计失败。如果测试不通过,会被认为测试成功;如果测试通过了,则被认为是测试失败。
exception  unittest. SkipTest (reason)
引发此异常以跳过一个测试。
通常来说,你可以使用  TestCase.skipTest() 或其中一个跳过测试的装饰器实现跳过测试的功能,而不是直接引发此异常。

被跳过的测试的 setUp() 和 tearDown() 不会被运行。被跳过的类的 setUpClass() 和 tearDownClass() 不会被运行。被跳过的模组的 setUpModule() 和 tearDownModule() 不会被运行。

猜你喜欢

转载自www.cnblogs.com/dmtz/p/10969371.html
今日推荐