-----------待测试数据----------
class MathMethod: def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b def sub(self): return self.a+self.b
---------测试case----------
import unittest from request_unitest.class_mathmethod import MathMethod class TestMathMethod(unittest.TestCase): def test_two_positive(self): result=MathMethod(1,2).add() try: #捕获异常 self.assertEqual(3,result) #断言 except AssertionError as e: print("报错%s"%e) def test_two_negtive(self): result=MathMethod(-2,-3).sub() self.assertEqual(-5,result) def test_two_dif(self): result=MathMethod(-1,2).add() self.assertEqual(-5,result) if __name__ == '__main__': unittest.main()------------执行测试------------
import unittest import HTMLTestRunnerNew #注意需要提导入下载好的报告插件 from request_unitest.test_mathmethod import TestMathMethod suite=unittest.TestSuite() loader=unittest.TestLoader() #加载测试用例 suite.addTest(loader.loadTestsFromTestCase(TestMathMethod)) #执行测试用例 # runner=unittest.TextTestRunner() # runner.run(suite) #将测试的结果写入到指定的文件中去 # with open('test.txt','w+') as file: # runner=unittest.TextTestRunner(file,'test',2) # runner.run(suite) #生成测试报告 with open('report.html','wb+') as file: runner=HTMLTestRunnerNew.HTMLTestRunner(file,2,title='cr-test',description='unittest',tester='chenran') runner.run(suite)