python单元测试中的设置/拆卸顺序是什么?

python单元测试中的设置/拆卸顺序是什么?,python,unit-testing,python-unittest,Python,Unit Testing,Python Unittest,我对python中的基本单元测试方法的理解存在差异。给定以下测试文件: import unittest, sys class TestStringMethods(unittest.TestCase): def setUp(self): self.mystring = "example string" def tearDown(self): del self.mystring def test_upper(self):

我对python中的基本单元测试方法的理解存在差异。给定以下测试文件:

import unittest, sys


class TestStringMethods(unittest.TestCase):

    def setUp(self):
        self.mystring = "example string"

    def tearDown(self):
        del self.mystring

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        with self.assertRaises(TypeError):
            s.split(2)
我的理解基于我所阅读的内容(“测试用例中名为setUp的方法在每个测试方法之前自动运行”,等等),我解释了事件的顺序,如:

1. set up self.mystring
2. run test_upper
3. tear down self.mystring

4. set up self.mystring
5. run test_isupper
6. tear down self.mystring

7. set up self.mystring
8. run test_split
9. tear down self.mystring
我的同事将这些文档解释为unittest的工作原理如下:

1. set up self.mystring
2. run test_upper
3. run test_isupper
4. run test_split
5. tear down self.mystring

这是一个非常重要的区别,哪一个是正确的?

你是对的。setup和teardown方法在每个测试用例之前和之后运行。这确保了每个测试都是独立运行的,所以测试的顺序无关紧要。在安装过程中创建的、在一次测试中更改的对象将为每个测试重新创建,因此测试不会相互影响。

如果您需要在所有情况之前设置一次,然后在所有情况之后将其拆除,则可以使用setUpClass/tearDownClass方法。但是,大多数情况下,您希望您描述的行为不会使单元测试相互干扰或相互依赖。


关于设置和拆卸,您是对的,它们在该类中的每个测试方法之前和之后运行。但是你的同事可能一直在考虑StudioCube和TurrDead类,这些类将在类中的任何测试方法被执行之前和在所有的测试方法完成之后运行一次。

所以默认行为是列表1-9,如何更改顺序来将所有的测试夹在中间,比如1-5列表?我假设
setUpClass()。。。在单个类运行中进行测试之前调用的类方法。setUpClass是以类作为唯一参数调用的,必须修饰为classmethod():