【Android自动化】unittest测试框架关于用例执行的几种方法

时间:2021-12-19 20:53:47
 # -*- coding:utf-8 -*-
import unittest class test(unittest.TestCase): def setUp(self):
print 'This is the setup msg' def tearDown(self):
print 'This is the teardown msg' def test1(self):
print 'This is the first testcase' def test2(self):
print 'This is the second testcase' def test3(self):
print 'This is the third testcase' 运行方法一:
if __name__ == '__main__':
unittest.main()
通过unittest.main()执行时,main会调用TextTestRunner中的run来执行 运行方法二:
suite = unittest.TestLoader().loadTestsFromTestCase(test)
unittest.TextTestRunner().run(suite)
通过创建一个测试套,将所有用例全部加载到测试套中,然后直接调用TextTestRunner方法能运行测试套(此时测试套中的用例执行还是无规则,不一定会按用例顺序进行执行) 运行方法三:
suite = unittest.TestSuite()
suite.addTest(test('test3'))
unittest.TextTestRunner().run(suite)
通过创建一个测试套,给测试套中增加一条测试用例,然后再调用TextTestRunner方法单独执行该测试用例 运行方法四:
suite = unittest.TestSuite()
suite.addTest(test('test3'))
suite.addTest(test('test1'))
unittest.TextTestRunner().run(suite)
通过创建一个测试套,给测试套中连续增加两条测试用例,然后再调用TextTestRunner方法执行该测试用例,此时会按照加载用例的顺序进行执行用例,但这种方法有点土,不强大(不建议使用) 运行方法五:
suite = unittest.TestSuite()
suite.addTests([test('test3'),test('test1'),test('test2')])
unittest.TextTestRunner().run(suite)
通过创建一个测试套,直接通过addTests()方法,添加一个用例列表进去,然后再调用TextTestRunner方法执行测试用例,此种方法能让unitest按照想要的执行顺序进行执行用例(对用例执行顺序有要求的此方法比较建议使用) 运行方法六:
def runTest(testcaseclass,testcase=[]):
suite = unittest.TestSuite()
for case in testcase:
suite.addTest(testcaseclass(case))
unittest.TextTestRunner().run(suite)
runTest(test,['test2','test3','test1']) 通过定义一个unitest运行方法,后面执行时直接调用该自定义方法,给上对应的赋值,程序就会按照想 要的执行程序进行执行(此种方法比较好,只要建立一个公共方法,后面在其它模块中直接调用,省去重复敲代码)