<p>您正在更改<code>setUp</code>方法中的<em>类属性</em>,并在<code>tearDown</code>中再次读取它,因为这两个都是类方法。然而,在您的测试中,您正在设置一个<em>实例</em>属性。在</p>
<p>你必须直接在类上设置它:</p>
<pre><code>type(self).result = 'ok'
</code></pre>
<p>或者</p>
^{pr2}$
<p>后者将它绑定到当前测试类,第一个选项允许它在子类中工作。在</p>
<p>演示:</p>
<pre><code>>>> import unittest
>>> class TestTemplate(unittest.TestCase):
... @classmethod
... def setUpClass(self):
... self.result = 'error'
... print "setUpClass"
... @classmethod
... def tearDownClass(self):
... print "The value of result is, ",self.result
... if self.result == 'ok':
... print "it is working"
... print "The value of cls result is : ", self.result
... print "TearDownClass"
...
>>> class MyTest(TestTemplate):
... def test_method_one(self):
... type(self).result = 'ok'
... print self.result
...
>>> unittest.main(exit=False)
setUpClass
ok
.The value of result is, ok
it is working
The value of cls result is : ok
TearDownClass
Ran 1 test in 0.000s
OK
<unittest.main.TestProgram object at 0x103945090>
</code></pre>
<p>但是,您通常希望避免在单个测试期间更改测试类状态。使用现有的<a href="https://docs.python.org/2/library/unittest.html#unittest.TestResult" rel="nofollow">test runner facilities</a>来跟踪测试结果;全部</p>
<p><code>setUpClass</code>和<code>tearDownClass</code>方法<em>可以应用于多个测试(取决于测试的运行方式),因此状态是共享的。在</p>