說說 Python TestCase 類中的鉤子方法

TestCase 類提供瞭如下 4 種鉤子方法:bash

方法 說明
setUp 在每個測試用例執行以前,會先執行此方法。通常用於初始化參數。
tearDown 在每個測試用例執行以後,會執行此方法。通常用於釋放資源。
setUpClass 在類中的全部測試用例執行以前,會先執行此方法。
tearDownClass 在類中的全部測試用例執行以後,會執行此方法。

示例:測試

class TestHookMethod(unittest.TestCase):
    '''測試鉤子方法'''

    @classmethod
    def setUpClass(cls):
        print('準備執行 TestHookMethod 中全部測試用例\n')

    @classmethod
    def tearDownClass(cls):
        print('TestHookMethod 中全部測試用例都已執行')

    def setUp(self):
        print('開始執行某個測試用例')

    def tearDown(self):
        print('某個測試用例已執行完畢')

    def test_a(self):
        self.assertEqual(1, 1)

    def test_b(self):
        self.assertEqual(2, 2)

複製代碼

運行結果:ui

準備執行 TestHookMethod 中全部測試用例 開始執行某個測試用例 某個測試用例已執行完畢 開始執行某個測試用例 某個測試用例已執行完畢 TestHookMethod 中全部測試用例都已執行spa

注意: setUpClass 與 tearDownClass 鉤子方法,必須加上 @classmethod 註解哦 O(∩_∩)O~code

相關文章
相關標籤/搜索