gpt4 book ai didi

python - setUp 和 tearDown 方法是否为每个方法运行或在 TestCase 的开始和结束时运行

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:34 24 4
gpt4 key购买 nike

属于同一个TestCase的测试方法是否会相互影响?

在 python unittest 中,我试图理解如果我在测试方法中更改变量,其他测试方法中的变量是否会更改。还是为每个方法运行 setUp 和 tearDown 方法,然后为每个方法重新设置变量?

我是说

AsdfTestCase(unittest.TestCase):
def setUp(self):
self.dict = {
'str': 'asdf',
'int': 10
}
def tearDown(self):
del self.dict

def test_asdf_1(self):
self.dict['str'] = 'test string'

def test_asdf_2(self):
print(self.dict)

所以我想问 test_asdf_2() 将打印哪个输出'asdf''test_string'

最佳答案

是的,setUp 和 tearDown 在测试用例类中的每个测试(即名称中以“test”开头的函数)之前运行。考虑这个例子:

# in file testmodule
import unittest

class AsdfTestCase(unittest.TestCase):
def setUp(self) : print('setUp called')
def tearDown(self) : print('tearDown called')
def test_asdf_1(self): print( 'test1 called' )
def test_asdf_2(self): print( 'test2 called' )

从命令行调用它:

 $ python3 -m unittest -v testmodule
test_asdf_1 (testmodule.AsdfTestCase) ... setUp called
test1 called
tearDown called
ok
test_asdf_2 (testmodule.AsdfTestCase) ... setUp called
test2 called
tearDown called
ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

(因此,是的,在您的示例中,它会弹出“asdf”,因为重新执行设置,覆盖由测试 2 引起的更改)

关于python - setUp 和 tearDown 方法是否为每个方法运行或在 TestCase 的开始和结束时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com