我现在有 3 个用例,如下
我现在需要一个变量,它在第一个用例里值是 2,在第二个用例里它的值是 4,第三个是 6,也就是累加 2,
我怎么去设置这样一个变量,是在 setup 里定义吗,求大神们指教
class TestNum(unittest.TestCase):
num = 0
def setUp(self):
TestNum.num+=2
def test_1(self):
print(self.num)
可以设置一个全局变量:
import unittest
COUNT = 0
class TestPara(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_01(self):
global COUNT
COUNT += 2
print(COUNT)
def test_02(self):
global COUNT
COUNT += 2
print(COUNT)
def test_03(self):
global COUNT
COUNT += 2
print(COUNT)
if __name__ == '__main__':
unittest.main()
分别输出: 2,4,6
class mytest(unittest.TestCase):
def setUp(self):
self.para = 0
print('setup: %s' % self.para)
def test01(self):
self.para = 2
print('t1: %s' % self.para)
def test02(self):
self.para = 4
print('t2: %s' % self.para)
def test03(self):
self.para = 6
print('t3: %s' % self.para)
def tearDown(self):
pass
结果:
Ran 3 tests in 0.000s
OK
setup: 0
t1: 2
setup: 0
t2: 4
setup: 0
t3: 6
class TestNum(unittest.TestCase):
num = 0
def setUp(self):
TestNum.num+=2
def test_1(self):
print(self.num)
class TestPara(unittest.TestCase):
def add2(func):
def wrapper(self):
if not hasattr(self.__class__,'c'): setattr(self.__class__,'c',0)
setattr(self.__class__,'c',getattr(self.__class__,'c')+2)
func(self)
return wrapper
@add2
def test_01(self):
print(self.__class__.c) # 2
def test_02(self):
print(self.__class__.c) # 2
@add2
def test_03(self):
print(self.__class__.c) # 4
if __name__ == '__main__':
unittest.main()
我想这样可能最大的解决继承的问题,他的孩子可能都能用,但我没试