本文將介紹單元測(cè)試的基礎(chǔ)版及使用unittest框架的單元測(cè)試。
完成以下需求的代碼編寫,并實(shí)現(xiàn)單元測(cè)試
賬號(hào)正確,密碼正確,返回{"msg":"賬號(hào)密碼正確,登錄成功"}
賬號(hào)和密碼任一為空,返回{"msg":"所有參數(shù)不能為空"}
賬號(hào)/密碼錯(cuò)誤,返回{"msg":"賬號(hào)/密碼錯(cuò)誤"}
基礎(chǔ)代碼實(shí)現(xiàn):
- 定義方法,實(shí)現(xiàn)基本需求:
account_right = "python"
pwd_right = "python666"
def userLogin(account=None, pwd=None):
if not account or not pwd:
return {"msg":"所有參數(shù)不能為空"}
if account != account_right or pwd != pwd_right:
return {"msg":"賬號(hào)/密碼錯(cuò)誤"}
if account == account_right and pwd == pwd_right:
return {"msg":"賬號(hào)密碼正確,登錄成功"}
return {"msg":"未知錯(cuò)誤,請(qǐng)聯(lián)系管理員"}
對(duì)代碼進(jìn)行驗(yàn)證,是否符合需求:
- 驗(yàn)證方法1:
print(userLogin("",""))
print(userLogin("python666","python"))
print(userLogin("","python666"))
print(userLogin("python",""))
print(userLogin("python","python666"))
驗(yàn)證結(jié)果:

image.png
分析:直接調(diào)用userLogin方法,獲取各種參數(shù)對(duì)應(yīng)的返回結(jié)果
- 驗(yàn)證方法2:
if __name__ == '__main__':
try:
assert userLogin("","") == {"msg":"所有參不能為空"}
assert userLogin("python666","python") == {'msg': '賬號(hào)/密碼錯(cuò)誤'}
assert userLogin("","python666") == {'msg': '所有參數(shù)不能為空'}
assert userLogin("python","") =={'msg': '所有參數(shù)不能為空'}
assert userLogin("python","python666") == {'msg': '賬號(hào)密碼正確,登錄成功'}
except Exception as e:
print("啊哦,測(cè)試失敗")
else:
print("恭喜!全部用例測(cè)試通過(guò)")
驗(yàn)證結(jié)果:

image.png
分析:通過(guò)assert判斷,寫入?yún)?shù)調(diào)取userLogin方法時(shí)得到的響應(yīng)和預(yù)期的響應(yīng)是否一致,如果一致就打印“全部通過(guò)”,如果有不一致的則會(huì)打印“測(cè)試失敗”
此處使用到的try...except...else組合:不論如何一定會(huì)執(zhí)行try下的代碼,如果有報(bào)錯(cuò)則執(zhí)行except下的代碼,如果沒有,則執(zhí)行else下的代碼。
- 驗(yàn)證方法3:使用unittest框架
另寫一個(gè)python文件,則需導(dǎo)入userLogin方法
import unittest
class MyTestCase(unittest.TestCase):
def test_empty(self):
expected = {"msg":"所有參數(shù)不能為空"}
actual = userLogin("","")
self.assertEqual(expected,actual)
def test_pwd_wrong(self):
expected = {"msg":"賬號(hào)/密碼錯(cuò)誤"}
actual = userLogin("python","python6")
self.assertEqual(expected,actual)
def test_account_empty(self):
expected = {"msg":"賬號(hào)/密碼錯(cuò)誤"}
actual = userLogin("python666","python")
self.assertEqual(expected,actual)
def test_login_ok(self):
expected = {"msg":"賬號(hào)密碼正確,登錄成功"}
actual = userLogin("python","python666")
self.assertEqual(expected,actual)
if __name__ == '__main__':
unittest.main()
驗(yàn)證結(jié)果:

image.png
分析:unittest框架中自帶assert,實(shí)現(xiàn)的效果和方法1、2并無(wú)不同,只不過(guò)這樣更好管理用例,可視化測(cè)試結(jié)果,以及產(chǎn)出測(cè)試報(bào)告。
self.assertEqual(expected,actual)即是,判斷expected和actual的返回值相等。
下一節(jié):如何使用unittest框架產(chǎn)出可視化測(cè)試報(bào)告