先建立一个Calc.py文件
class Calc(object):
def add(self,x,y,*d):
#加法计算
result = x+y
for i in d:
result += i
return result
def sub(self,x,y,*d):
#减法计算
resilt =x-y
for i in d:
resilt -=i
return resilt
@classmethod
def mul(cls,x,y,*d):
#乘法计算
resilt =x*y
for i in d:
resilt *=i
return resilt
@staticmethod
def div(x,y,*d):
#除法计算
if y!=0:
result = x/y
else:
return -1
for i in d:
if i !=0:
result/=i
else:
return -1
return result
2、在建立一个Mytest.py文件:
import unittest
from Cale import Calc
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('单元测试前,创建Case类的实例')
cls.c=Calc()
#具有的测试用例,一定要有test开头
def test_add(self):
print('run add()')
self.assertEqual(MyTest.c.add(1,2,3),6,'test add fail')
def test_sub(self):
print('run sub()')
self.assertEqual(MyTest.c.sub(2,1,3),-2,'test sub fail')
def test_mul(self):
print('run mul()')
self.assertEqual(Calc.mul(2,3,5),30,'test mul fail')
def test_div(self):
print('run div()'),
self.assertEqual(Calc.div(8,2,4),1,'test div fail')
if __name__ == '__main__':
suite = unittest.TestSuite()
# unittest.main()
suite.addTest(MyTest('test_mul'))
suite.addTest(MyTest('test_div'))
suite.addTest(MyTest('test_add'))
suite.addTest(MyTest('test_sub'))
runner = unittest.TextTestRunner()
runner.run(suite)