python中自动化测试框架unittest
import unittest
class Test1(unittest.TestCase):
def setUp(self):
print("login")
def test_01(self):
self.assertEqual(1,1)
def test_02(self):
self.assertEqual(2,3)
def tearDown(self):
print("close")
if __name__ == '__main__':
#verbosity=2主要是详细的输出每个测试详细执行结果
unittest.main(verbosity=2)
执行结果:
login
close
login
close
Failure
Traceback (most recent call last):
File "D:\PyCharm\learnPy\unnitest\test.py", line 11, in test_02
self.assertEqual(2,3)
AssertionError: 2 != 3
(1)每个测试用例以test开头,否则无法识别
(2)在unittest.main()中加verbosity
参数可以控制输出的错误报告的详细程度,默认是1
,如果设为0
,则不输出每一用例的执行结果,即没有上面的结果中的第1行;如果设为2
,则输出详细的执行结果
(3)setUp和tearDown在每次执行case前后都执行了一次。
如果想要在所有case执行之前准备一次环境,并在所有case执行结束之后再清理环境,我们可以用setUpClass()
与tearDownClass()
:
import unittest
class Test1(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("login")
def test_01(self):
self.assertEqual(1,1)
def test_02(self):
self.assertEqual(2,3)
@classmethod
def tearDownClass(cls):
print("close")
if __name__ == '__main__':
#verbosity=2主要是详细的输出每个测试详细执行结果
unittest.main(verbosity=2)
输出结果:
login
Failure
Traceback (most recent call last):
File "D:\PyCharm\learnPy\unnitest\test1.py", line 11, in test_02
self.assertEqual(2,3)
AssertionError: 2 != 3
close
如果想跳过那个case,可以使用skip装饰器
import unittest
class Test1(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("login")
def test_01(self):
self.assertEqual(1,1)
def test_02(self):
self.assertEqual(2,3)
@unittest.skip('not run')
def test_03(self):
self.assertEqual(4,4)
@classmethod
def tearDownClass(cls):
print("close")
if __name__ == '__main__':
#verbosity=2主要是详细的输出每个测试详细执行结果
unittest.main(verbosity=2)
这样执行case如果需要按一定执行顺序,如先执行A,再执行B时,需要把case添加到testsuit中,py文件中含多个class,我们需要批量运行case时,可以把case添加到testsuit
import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("befor case")
def test_01(self):
print("01")
def test_02(self):
print("02")
def test_03(self):
print("03")
def test_04(self):
print("04")
@classmethod
def tearDownClass(cls):
print("after case")
if __name__ == '__main__':
suit=unittest.TestSuite()
# suit.addTest(Test("test_01"))
# suit.addTest(Test("test_02"))
# suit.addTest(Test("test_03"))
#将测试用例按照自己想要的执行顺序添加到testsuit中
testcast=[Test("test_01"),Test("test_04"),Test("test_03")]
suit.addTests(testcast)
unittest.TextTestRunner(verbosity=2).run(suit)
执行结果:
befor case
test_01 (__main__.Test) ... ok
01
test_04 (__main__.Test) ... ok
04
test_03 (__main__.Test) ... ok
03
after case
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
查找当前目录下test包中的testcast
suite = unittest.defaultTestLoader.discover(basedir + '/test/testcase')
unittest.TextTestRunner(verbosity=2).run(suit)