zoukankan      html  css  js  c++  java
  • setUp和tearDown及setUpClass和tearDownClass的用法及区别

    转自:https://blog.csdn.net/weixin_41003801/article/details/79793037?utm_source=copy

    知道unittest单元测试框架的朋友应该都知道,

    执行继承了unittest.TestCase的类下每个test开头的方法(就是用例)时,都会执行setUp和tearDown,如下面的例子所示:  

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import  unittest
     
    class  TestSetupTeardown(unittest.TestCase):
         def  setUp( self ):
             print ( '连接数据库成功...' )
         def  tearDown( self ):
             print ( '关闭数据库。' )
     
         def  test_a( self ):
             print ( 'test_a' )
     
         def  test_b( self ):
             print ( 'test_b' )
     
    if  __name__  = =  '__main__' :
         unittest.main()

    setUp连接数据库,tearDown关闭数据库,这样反复执行,无疑是会增加数据库服务器资源的损耗,且浪费时间

    能不能只执行一次呢?

    答案是肯定的,通过装饰器就可以实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import  unittest
     
    class  TestSetupTeardown(unittest.TestCase):
         @classmethod
         def  setUpClass( cls ):
             print ( '连接数据库成功...' )
         @classmethod
         def  tearDownClass( cls ):
             print ( '关闭数据库。' )
     
         def  test_a( self ):
             print ( 'test_a' )
     
         def  test_b( self ):
             print ( 'test_b' )
     
    if  __name__  = =  '__main__' :
         unittest.main()

     
  • 相关阅读:
    HDU 1813 Escape from Tetris
    BZOJ 2276 Temperature
    BZOJ 4499 线性函数
    BZOJ 3131 淘金
    HDU 5738 Eureka
    POJ 2409 Let it Bead
    POJ 1286 Necklace of Beads
    POJ 1696 Space Ant
    Fox And Jumping
    Recover the String
  • 原文地址:https://www.cnblogs.com/amim/p/14696227.html
Copyright © 2011-2022 走看看