Python+selenium之跳过测试和预期失败

在运行测试时,需要直接跳过某些测试用例,或者当用例符合某个条件时跳过测试,又或者直接将测试用例设置为失败。unittest单元测试框架提供了实现这些需求的装饰器。

1.unittest.skip(reason)

无条件地跳过装饰的测试,说明跳过测试的原因

2.unittest.skipIf(condition,reason)

如果条件为真时,跳过装饰的测试。

3.unittest.skipUless(condition,reason)

跳过装饰的测试,除非条件为真

4.unittest.expectedFailure()

测试标记为失败。不管执行结果是否失败,统一标记为失败。

代码如下:

 1 # # coding =utf-8
 2 # # calculator
 3 #
 4 # class Count ():
 5 #     def __init__(self, a, b):
 6 #         self.a = int (a)
 7 #         self.b = int (b)
 8 #
 9 #     def add(self):
10 #         return self.a + self.b
11 #
12 #     def sub(self):
13 #         return self.a - self.b
14 import unittest
15 
16 
17 class MyTest (unittest.TestCase):
18     def setUp(self):
19         pass
20 
21     def tearDown(self):
22         pass
23 
24     @unittest.skip ("直接跳过测试")
25     def test_skip(self):
26         print("test aaa")
27 
28     @unittest.skipIf (3 > 2, "当条件为True时,跳过测试")
29     def test_skip_if(self):
30         print('test bbb')
31 
32     @unittest.skipUnless (3 > 2, "当条件为True时,执行测试")
33     def test_skip_unless(self):
34         print('test ccc')
35 
36     @unittest.expectedFailure
37     def test_expected_failure(self):
38         assertEqual (2, 3)
39 
40 
41 if __name__ == '__main__':
42     unittest.main ()

如上:第一条测试用例通过@unittest.skip()装饰,直接跳过不执行。

           第二条用例通过@unittest.skipIf()装饰,当条件为真时不执行,3>2条件为真(True),跳过不执行。

           第三条用例通过@unittest.skipUnless()z装饰,当条件为真时执行,判断3>2条件为真(True),第三条用例执行。

           第四条用例通过@unittest.expectedFailure装饰,不管执行结果是否失败,统一标记为失败,但不会抛出错误信息。

这些方法同样可以作用测试类,只需要将他们定义在测试类上面即可。

 1 import unittest
 2 
 3 
 4 @unittest.skip ("直接跳过该测试类")
 5 class MyTest (unittest.TestCase):
 6     def setUp(self):
 7         pass
 8 
 9     def tearDown(self):
10         pass
11 
12     @unittest.skip ("直接跳过测试")
13     def test_skip(self):
14         print("test aaa")
15 
16     @unittest.skipIf (3 > 2, "当条件为True时,跳过测试")
17     def test_skip_if(self):
18         print('test bbb')
19 
20     @unittest.skipUnless (3 > 2, "当条件为True时,执行测试")
21     def test_skip_unless(self):
22         print('test ccc')
23 
24     @unittest.expectedFailure
25     def test_expected_failure(self):
26         assertEqual (2, 3)
27 
28 
29 if __name__ == '__main__':
30     unittest.main ()

 

 

           

posted @ 2017-09-23 16:11  木棉花的漂泊  阅读(1157)  评论(0编辑  收藏  举报