Python Unittest和对象初始化

Tom*_*Tom 3 python unit-testing python-3.x python-unittest

我的Python版本是3.5.1

我有一个简单的代码(tests.py):

import unittest

class SimpleObject(object):
    array = []

class SimpleTestCase(unittest.TestCase):

    def test_first(self):
        simple_object = SimpleObject()
        simple_object.array.append(1)

        self.assertEqual(len(simple_object.array), 1)

    def test_second(self):
        simple_object = SimpleObject()
        simple_object.array.append(1)

        self.assertEqual(len(simple_object.array), 1)

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

如果我用命令'python tests.py'运行它,我会得到结果:

.F
======================================================================
FAIL: test_second (__main__.SimpleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 105, in test_second
    self.assertEqual(len(simple_object.array), 1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.003s

FAILED (failures=1)
Run Code Online (Sandbox Code Playgroud)

为什么会这样?以及如何解决它.我希望每个测试运行都是独立的(每个测试都应该通过),但它并不像我们所看到的那样.

Bry*_*ley 5

该数组由该类的所有实例共享.如果您希望数组对于实例是唯一的,则需要将其放在类初始值设定项中:

class SimpleObject(object):
    def __init__(self):
        self.array = []
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看此问题:类变量是否在python中的所有实例之间共享?