我想在测试方法中为类属性设置一个值,并在另一个测试方法中使用具有相同类属性的值。当我通过使用方法执行测试用例以正常方式尝试时run
,得到错误为AttributeError: 'Unit' object has no attribute 'b'
. 无论如何,我通过使用global
变量找到了其他解决方案,并通过将类分配给变量找到了另一种解决方案。我可以知道为什么我无法检索我使用另一种方法设置的类属性的原因吗?另外,你能帮我解释一下run
方法的实际过程吗?在此先感谢。
这是我尝试过的示例代码:
import unittest
class Unit(unittest.TestCase):
def test_i(self):
self.b=20
def test_j(self):
print self.b
suite=unittest.TestLoader().loadTestsFromTestCase(Unit)
unittest.TextTestRunner(verbosity=2).run(suite)
test_i (__main__.Unit) ... ok
test_j (__main__.Unit) ... ERROR
======================================================================
ERROR: test_j (__main__.Unit)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#52>", line 5, in test_j
AttributeError: 'Unit' object has no attribute 'b'
----------------------------------------------------------------------
Ran 2 tests in 0.078s
FAILED (errors=1)
<unittest.runner.TextTestResult run=2 errors=1 failures=0>
#The two ways which I solved...
#1.By Assinging class to a variable
import unittest
class Unit(unittest.TestCase):
def test_i(self):
Class=Unit
Class.b=20
def test_j(self):
print self.b
suite=unittest.TestLoader().loadTestsFromTestCase(Unit)
unittest.TextTestRunner(verbosity=2).run(suite)
test_i (__main__.Unit) ... ok
test_j (__main__.Unit) ... 20
ok
----------------------------------------------------------------------
Ran 2 tests in 0.094s
OK
<unittest.runner.TextTestResult run=2 errors=0 failures=0>
#2.By using global attribute,but I need the class attribute value to be set and retrieved
import unittest
class Unit(unittest.TestCase):
def test_i(self):
global b,
b=20
def test_j(self):
print b
suite=unittest.TestLoader().loadTestsFromTestCase(Unit)
unittest.TextTestRunner(verbosity=2).run(suite)
test_i (__main__.Unit) ... ok
test_j (__main__.Unit) ... 20
ok
----------------------------------------------------------------------
Ran 2 tests in 0.063s
OK
<unittest.runner.TextTestResult run=2 errors=0 failures=0>