python-为每个方法或在TestCase的开头和结尾处运行setUp和tearDown方法
作者:互联网
属于同一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
(因此,是的,在您的示例中,由于将重新执行setUp,因此会覆盖“ asdf”,从而覆盖由测试2引起的更改)
标签:python-unittest,python 来源: https://codeday.me/bug/20191025/1925773.html