1. 程式人生 > >python單元測試

python單元測試

複雜執行

匯入unittest模組中的TestCase方法

 
 

寫好一個方法

 
 

寫好一個類來執行測試用例 self.assertEqual(預期結果,實際結果,實際和預期對不上時預設提示可省)

 
 

例項化類

 
 

執行

eg:
 1 from unittest import TestCase
 2 
 3 def calc(a,b):
 4     c = a//b
 5     return c
 6 
 7 class MyTest(TestCase):
 8     def calc1(self):
 9         #正常的測試用例
10         res = calc(4,2)
11 self.assertEqual(2,res,'預期結果和實際結果不符合 預期結果是 2 實際結果是%s'%res)#斷言 12 13 def calc2(self): 14 # 不正常的測試用例 15 res = calc(5, 1) 16 self.assertEqual(1, res) 17 18 m = MyTest() 19 m.calc1() 20 m.calc2()

用unittest.main()全部執行,用例必須是以test開頭

 1 import unittest
 2 from
unittest import TestCase 3 4 def calc(a,b): 5 c = a//b 6 return c 7 8 class MyTest(TestCase): 9 def test_calc1(self): 10 #正常的測試用例 11 res = calc(4,2) 12 self.assertEqual(2,res,'預期結果和實際結果不符合 預期結果是 2 實際結果是%s'%res)#斷言 13 14 def test_calc2(self): 15 #
不正常的測試用例 16 res = calc(5, 1) 17 self.assertEqual(1, res) 18 unittest.main()

執行結果:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/ihealth-qa/PycharmProjects/untitled/test.py
.F
======================================================================
FAIL: test_calc2 (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/ihealth-qa/PycharmProjects/untitled/test.py", line 17, in test_calc2
self.assertEqual(1, res)
AssertionError: 1 != 5

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)

Process finished with exit code 1