1、命名规则

以test_开头

1 impot unittest
2 
3 class Cs(unittest.TestClass):
4     def test_01(self):
5         pass

 

2、装饰器:

@classmethod  只执行一次

@unitest.skip(reason) 无条件跳过执行测试,描述为什么跳过测试

@unittest.skipif(conditition,reasonconditition是true时跳过测试

@unittest.skipunless(condition,reason) condition不是true时跳过测试

@expected failure 使用@unittest.expectedFailure装饰器,如果test失败了,不计入失败的case里面

 1 import unittest
 2 
 3 
 4 class TsetCase(unittest.TestCase):
 5     # 执行用例前
 6     @classmethod
 7     def tearDownClass(cls):
 8         print('测试结束了!!')
 9 
10     @classmethod
11     def setUpClass(cls):
12         print('开始测试了!!')
13 
14     @unittest.skip('不需要执行这条测试用例')
15     def test_01(self):
16         a = 1
17         b = 2
18         self.assertEqual(a + b, 3)
19 
20 if __name__ == '__main__':
21     unittest.main()

参考来源:https://www.jianshu.com/p/ba5dbcb5d71b

 

3‘、固定套件:

unittest module包含了编写运行unittest的功能,自定义的test class都要集成

unitest.TestCase类,test method要以test开头,运行顺序根据名字排序,特殊方法:

①tearDownClass(cls)  执行测试前函数

②setUpClass(cls)     执行用例后函授

③setUp(self)        每次执行测试都要执行一次

④tearDown(self)    每次执行测试完成后执行一次

运行测试方法:

unittest.main()               执行所有的case   

unittest.TestSuite()             测试套件

runner = unittest.TextTestRunner()      实例化TextTestRunner  

import unittest


class TsetCase(unittest.TestCase):
    # 执行用例前
    @classmethod
    def tearDownClass(cls):
        print('测试结束了!!')

    @classmethod
    def setUpClass(cls):
        print('开始测试了!!')

    def setUp(self):
        print('开始执行')

    def tearDown(self):
        print('执行完成')

    @unittest.skip('不需要执行这条测试用例')
    def test_01(self):
        a = 1
        b = 2
        self.assertEqual(a + b, 3)

    def test_02(self):
        a = 2
        b = 3
        self.assertEqual(a+b,4)

if __name__ == '__main__':
    # unittest.main()
    # suite = unittest.TestSuite()
    # suite.addTest(TsetCase('test_01'))
    # runner = unittest.TextTestRunner()
    # runner.run(suite)
    ljwj = r'F:\项目\京东登陆\TestCases'
    cszx = unittest.defaultTestLoader.discover(start_dir=ljwj , pattern='test_*.py')
    runner = unittest.TextTestRunner()
    runner.run(cszx)

     

posted on 2020-01-03 18:25  小和尚不吃素  阅读(223)  评论(0编辑  收藏  举报