2015-08-21 26 views
2

我在Python中的基本单元测试方法的理解存在差异。鉴于低于这个测试文件:python单元测试中setUp/tearDown的顺序是什么?

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) 

我根据我读过的理解(“方法命名为设立在测试用例是自动运行的,每个测试方法之前。” 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 

我的同事解释文档的话说,单元测试的工作原理如下:

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

这是一个非常重要的区别,其中一个 是对的?

回答

1

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

1

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

+0

所以默认行为是列表1-9,您如何更改命令以将所有测试夹在中间,如1-5列表?我假设 'setUpClass()... 在单个类运行中的测试之前调用的类方法。 setUpClass被作为唯一参数调用,并且必须作为classmethod()进行装饰:' – codyc4321

+1

codyc4321 - 正确。我不能添加一个东西:) –

3

Python Unittest Docs

你说得对有关安装和拆卸,他们之前和类中的每个测试方法之后运行。但是你的同事可能一直在考虑setUpClass和tearDownClass,在类中的任何测试方法被执行之前以及在所有的测试方法完成之后,它们将分别运行一次。

+0

我们都在不同的方式:)谢谢你们 – codyc4321