unittest的基本使用方法
1.import unittest
2.定义一个继承自unittest.TestCase的测试用例类
3.定义setUp和tearDown,在每个测试用例前后做一些辅助工作。
4.定义测试用例,名字以test开头。
5.一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。
6.调用unittest.main()启动测试
7.如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,这时可以添加-v参数显示详细信息。
Unittest断言
作用:期望结果与实际结果比较,来判断该case是通过还是失败
但是不影响其他的case执行。
import unittest
import HTMLTestRunner
class Test002(unittest.TestCase):
#before run test
def setUp(self):
print 'Case Before'
pass
#after run test
def tearDown(self):
print 'Case After'
pass
#test 1
def test_Case1(self):
a = 3
b = 2
self.assertEqual(a+b,6,'test_case1 is fail.')
print "test_case1 is successfule."
#test 2
def test_Case2(self):
a = 2
b = 3
self.assertEqual(a*b,6,'test_case2 is fail.')
print "test_case2 is successfule."
#test 3
def test_Case3(self):
a = 5
b = 3
self.assertEqual(a-b,2,'test_case2 is fail.')
print "test_case2 is successfule."
if __name__ == '__main__':
#unittest.main()
suite=unittest.TestSuite()#define test suite
suite.addTest(Test002('test_Case1'))
suite.addTest(Test002('test_Case2'))
suite.addTest(Test002('test_Case3'))
#unittest.TextTestRunner(verbosity=2).run(suite)
outfile = open("Report.html", "w")
runner = HTMLTestRunner.HTMLTestRunner(
stream=outfile,
title='Test Report',
description='test one.'
)
runner.run(suite)