整理了一个单元测试的完整流程,觉得很不错。

一个 test case
类应该派生自 unittest.TestCase正常的的test case的调用顺序为

 unittest单元测试流程-风君雪科技博客

from __future__ import print_function
import unittest
 
def setUpModule():
    print(“setUpModule”)
  
def tearDownModule():
    print(“tearDownModule”)
     
class MyTestCase(unittest.TestCase):
 
    def setUp(self):
        super(MyTestCase, self).setUp()
        self.addCleanup(self.my_cleanup)
         
        print()
        print(“++++ setup”)
 
    def tearDown(self):
        super(MyTestCase, self).tearDown()
        print(“++++ tearDown”)
        raise Exception()
         
    def my_cleanup(self):
        print(“++++ my_cleanup”)
         
    def test_case_1(self):
        print(“++++ test case 1”)
 
    def test_case_2(self):
        print(“++++ test case 2”)
           
    @classmethod
    def setUpClass(cls):
        print(“setUpClass”)
 
    @classmethod
    def tearDownClass(cls):
        print()
        print(“tearDownClass”)

运行结果
setUpModule
setUpClass
 
++++ setup
++++ test case 1
++++ tearDown
++++ my_cleanup
 
++++ setup
++++ test case 2
++++ tearDown
++++ my_cleanup
 
tearDownClass
tearDownModule

来自 <http://www.2cto.com/kf/201409/330721.html>