python 单元测试中 setUp/tearDown 的顺序是什么?

what is the order of setUp/tearDown in python unit tests?

我对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)

我根据阅读的内容("Methods named setUp in a TestCase are run, automatically, before every test method."、http://gettingstartedwithdjango.com/en/lessons/testing-microblog/#toc1 等)理解事件的顺序,例如:

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 方法是 运行 之前和之后 each 测试用例。这确保每个测试都是 运行 孤立的,因此测试的顺序无关紧要。在设置期间创建并在一次测试期间更改的对象会为每个测试重新创建,因此测试不会相互影响。

方法setUpClass/tearDownClass 如果您需要在所有案例之前设置一次并在所有案例之后拆除它,可以使用方法。但大多数时候,您需要您描述的行为,以便单元测试不会相互干扰或相互依赖。

Python Unittest Docs

你对 setUp 和 tearDown 的看法是正确的,它们 运行 在每个测试方法之前和之后 class。但是您的同事可能一直在考虑 setUpClass 和 tearDownClass,它们会分别 运行 在执行 class 中的任何测试方法之前和完成所有测试方法之后。