7

我想使用self.attr一个unittest.TestCase类,但它似乎在测试之间不是持久的:

import unittest

class TestNightlife(unittest.TestCase):
    _my_param = 0

    def test_a(self):
        print 'test A = %d' % self._my_param
        self._my_param = 1

    def test_b(self):
        print 'test B = %d' % self._my_param
        self._my_param = 2

if __name__ == "__main__":
    unittest.main()

这给出了以下输出:

test A = 0
test B = 0

unittest.TestCase测试运行之间的实例是否发生变化?为什么?

4

1 回答 1

9

它是这样工作的,因为 unittest.main() 为每个测试创建单独的对象(在这种情况下创建了两个对象)。

关于你的动机:测试不应该改变全局状态。您应该在 tearDown 测试或测试之前将全局状态恢复为状态。如果测试正在改变全局状态,这是非常有问题的,你迟早会陷入无法预测的场景。

import unittest

class TestNightlife(unittest.TestCase):
    _my_param = 0

    def test_a(self):
        print 'object id: %d' % id(self)
        print 'test A = %d' % self._my_param
        self._my_param = 1

    def test_b(self):
        print 'object id: %d' % id(self)
        print 'test B = %d' % self._my_param
        self._my_param = 2

if __name__ == "__main__":
    unittest.main()

输出:

object id: 10969360
test A = 0
.object id: 10969424
test B = 0
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
于 2012-05-13T08:46:37.413 回答