单元测试中的拆卸方法 python

teardown method in unittest python

我是 python 的新手。我阅读了单元测试文档。在有关 tearDown() 方法的文档中,我发现以下几行

"This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state."

这句话表达了什么意思?你能否借助一些很好的例子让我理解我的意思,内部语句会造成破坏?

提前致谢。

编辑:

我得到了一些答案,但它们很简单。我需要一些例子,其中涉及一些状态,比如涉及数据库的测试等等。

这意味着无论您的测试方法是通过还是失败(引发异常),都会执行 tearDown() 方法。

例如:

def tearDown():
    print 'In teardown: cleaning up'

def test_Example1():
    try:
        result = 2 / 0
    except ZeroDivisionError as e:
        raise e

def test_Example2():
    try:
       result = 2 / 2
    except ZeroDivisionError as e:
        raise e   

test_Example1运行时,它会抛出一个ZeroDivisionError,然后执行tearDown(),在控制台打印In teardown: cleaning uptest_Example2 不会 引发 ZeroDivisionError 异常,但无论如何 tearDown() 仍将执行。

编辑 我对Python的数据库模块并不完全熟悉,但这应该足以让球滚动...

def tearDown():
    print 'In teardown: cleaning up'

def test_do_database_task():
    db = sqlite3.connect(DB_NAME)        
    try:
        # code related to task at hand
    except:
        raise Exception("Error in connection!")
    finally:
        closeDb(db)

来自 OP:

"This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state."

这传达的第一件事是,您可以确定无论在您的测试方法中发生什么,都会调用 teardown。因此,这意味着您应该在您的测试方法中有任何拆解代码,您应该将它移动到teardown方法中。

但是,如果您的测试方法确实有异常,这可能意味着您的测试实例的状态在不同的测试运行中可能不同,teardown 方法必须考虑到这一点,或者您必须构建您的代码,使其始终有效。

一个例子可能是您的测试代码涉及在数据库中创建表。如果出现异常,则可能并非所有表都已创建,因此 teardown 应确保它不会尝试删除不存在的表。但是,更好的方法可能是 setup 开始事务并 teardown 回滚事务。