unittest基础
测试用例的管理
import unittest
class MyTest(unittest.TestCase): # 继承 unittest.TestCase
def tearDown(self):
# 每个测试用例执行之后做操作
print('每个案例测试后执行')
def setUp(self):
# 每个测试用例执行之前做操作
print('每个案例测试前执行')
@classmethod
def tearDownClass(self):
# 必须使用 @ classmethod 装饰器, 所有 test 运行完后运行一次
print('所有案例测试后执行')
@classmethod
def setUpClass(self):
# 必须使用@classmethod 装饰器,所有 test 运行前运行一次
print('所有案例测试前执行')
def test_a_run(self):
print("test_a")
self.assertEqual(1, 1) # 测试用例
def test_b_run(self):
print("test_b")
self.assertEqual(2, 2) # 测试用例
if __name__ == '__main__':
unittest.main() # 运行所有的测试用例
用 TestLoader 加载 TestCase 到 TestSuite
import os
from selenium import webdriver
#import HTMLTestRunner
import unittest
from lab6 import MyTest
dir=os.getcwd()
outfile=open(dir+"\myreport.html","wb+")
mytest1=unittest.TestLoader().loadTestsFromTestCase(MyTest)
alltest=unittest.TestSuite([mytest1])
unittest.TextTestRunner().run(alltest)
用HTMLTestRunner生成html报告
在python安装路径lib文件夹中放入HTMLTestRunner.py文件
此时便可 import HTMLTestRunner.py
代码模板
import os
from selenium import webdriver
import HTMLTestRunner
import unittest
from mytest1class import mytest1class
from mytest2class import mytest2class
dir=os.getcwd()
outfile = open(dir+"\myreport.html","wb+")
mytest1 =unittest.TestLoader().loadTestsFromTestCase(mytest1class)
mytest2=unittest.TestLoader().loadTestsFromTestCase(mytest2class)
alltest = unittest.TestSuite([mytest1,mytest2])
runner=HTMLTestRunner.HTMLTestRunner(stream=outfile,title="my test report",
description="smoke tests")
runner.run(alltest)