self.attr在unittest.TestCase中的测试之间重置

Jon*_*han 7 python unit-testing

我想用一个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()
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

test A = 0
test B = 0
Run Code Online (Sandbox Code Playgroud)

unittest.TestCase测试之间的更改实例是否运行?为什么?

Tom*_*cki 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()
Run Code Online (Sandbox Code Playgroud)

输出:

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

OK
Run Code Online (Sandbox Code Playgroud)