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



我对python中的基本unittest方法的理解有差异。给定下面的测试文件:

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)

我的理解基于我读过的内容("在TestCase中名为setUp的方法在每个测试方法之前自动运行",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方法。这确保了每个测试都是独立运行的,因此测试的顺序无关紧要。在安装过程中创建的对象在一个测试期间更改,将为每个测试重新创建,因此测试不会相互影响。

Python Unittest Docs

关于setUp和tearDown你是对的,它们在该类中的每个测试方法之前和之后运行。但是您的同事可能已经想到了setUpClass和tearDownClass,它们将分别在类中的任何测试方法执行之前和所有测试方法完成之后运行一次。

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

最新更新