1、Python標準庫中模塊unittest提供了代碼測試工具
單元測試:覈實函數的某個方面沒有問題
測試用例:一組單元測試,覈實函數在各種情形下的行爲都符合要求
全覆蓋測試:一整套單元測試,涵蓋了各種可能的函數使用方式
2、unittest.main()讓Python運行當前文件的中的測試,運行測試文件時,所有以test_打頭的方法都自動運行。
3、編寫測試用例:先導入模塊unittest以及要測試的函數,再創建一個繼承unittest.TestCase的類,並編寫一系列方法對函數行爲的不同方面進行測試
練習1
def address(city,country):
site=city+','+country
return site
print(address('Santiago','Chile'))
練習2
def address(city,country):
site=city+','+country
return site
import unittest
from city_functions import address
class CityTest(unittest.TestCase):
"""測試city_functions.py"""
def test_city_functions(self):
site=address('Santiago','Chile')
self.assertEqual(site,'Santiago,Chile')
unittest.main()
練習3
def address(city,country,population):
message=city+','+country+"-population "+population
return message
import unittest
from city_functions import address
class CityTest(unittest.TestCase):
"""測試city_functions.py"""
def test_city_functions(self):
site=address('Santiago','Chile',"5000000")
self.assertEqual(site,'Santiago,Chile-population 5000000')
unittest.main()