Python单元测试和对象初始化
Python Unittest and object initialization
我的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()
如果我运行它用命令'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)
为什么会这样?以及如何修复它。我希望每个测试 运行 都是独立的(每个测试都应该通过),但事实并非如此。
该数组由 class 的所有实例共享。如果你想让数组对一个实例来说是唯一的,你需要把它放在 class 初始化器中:
class SimpleObject(object):
def __init__(self):
self.array = []
有关更多信息,请查看此问题:class variables is shared across all instances in python?
我的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()
如果我运行它用命令'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)
为什么会这样?以及如何修复它。我希望每个测试 运行 都是独立的(每个测试都应该通过),但事实并非如此。
该数组由 class 的所有实例共享。如果你想让数组对一个实例来说是唯一的,你需要把它放在 class 初始化器中:
class SimpleObject(object):
def __init__(self):
self.array = []
有关更多信息,请查看此问题:class variables is shared across all instances in python?