是否为每个方法运行setUp和tearDown方法,或者在TestCase的开头和结尾运行

mel*_*ike 4 python python-unittest

属于同一 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)
Run Code Online (Sandbox Code Playgroud)

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

Tas*_*nou 5

是的,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' )
Run Code Online (Sandbox Code Playgroud)

从命令行调用它:

 $ 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
Run Code Online (Sandbox Code Playgroud)

(因此,是的,在您的示例中,由于重新执行了setUp,它会显示“asdf”,从而覆盖测试2引起的更改)