單元測試 unittest 斷言 判斷

2022-07-12 00:21:09 字數 2487 閱讀 4062

# 單元測試,**測試**

針對函式、類,檢測他的某個方面是否有問題的測試

開發測試用例是一組單元測試,每個單元測試是一起核實函式和類在各種情況下的行為都符合要求

為什麼要做單元測試?

1、單元測試 ->整合測試 ->

2、從底層發現bug,越早發現bug越好解決避免後期重構,節約時間、經費

3、全覆蓋特別困難,只針對重要的行為編寫測試

4、為了做單元測試,unittest框架,單元測試框架

1、建立乙個login.py

def login_check(username,password):

""":param username:賬號

:param password:密碼

:return:

"""if 6 <= len(password) <= 18:

if username == 'python34' and password == 'lemonban':

return

else:

return

else:

return

# __name__ 是模組的特殊變數

# 當直接執行當前模組的時候__name__='__main__'

# 當被其他模組匯入的時候__name__ = 模組名

# pass佔位符,什麼都不是,表示跳過

if __name__ == '__main__':

pass

2、建立乙個test_case.py

匯入unittese,匯入被檢測函式或者類

一般系統模組放在最上面

第三方模組放在系統模組的下面

自己寫的模組放在最下面

import unittest

from login import login_check

# 建立測試類,繼承unittest.tesecase類,測試用例

class testlog(unittest.testcase):

"""測試登入功能

"""# 3、如果有初始(前置)條件和結束(後置)條件,重寫腳手架(fixture)方法

# 4、定義單元測試函式,函式名要以test開頭

def test_log_ok(self):

"""賬號密碼正確

:return:

"""# 1、測試資料

test_data =

# 期望資料

expect_data =

# 測試步驟

# 執行函式-,**解包,鍵相同,相當於把test_data中的兩個值傳給了login_check

res = login_check(**test_data)

# 3、斷言(判斷)assert下的equal是判斷是否相同

self.assertequal(expect_data, res)

# 如果不相等會丟擲asserterror,斷言錯誤

print('第一條用例')

def test_log_password_error(self):

"""賬號正確,密碼錯誤

:return:

"""# 1、測試資料

test_data =

# 期望結果

expected =

# 2、測試步驟

res = login_check(**test_data)

# 3、斷言

self.assertequal(expected, res)

print("第二條用例")

def test_password_ok_pass_error(self):

test_date =

expected =

res = login_check(**test_date)

self.assertequal(res,expected)

print('第三條用例')

def test_password_lenth_little(self):

test_data =

expected =

res = login_check(**test_data)

self.assertequal(expected,res)

print('第四條用例')

def test_password_lenth_blg(self):

test_data =

expected =

res = login_check(**test_data)

self.assertequal(expected,res)

print('第五條用例')

# 5、呼叫unittese.main()來執行測試用例

if __name__ == '__main__':

a = 1

# 會自動收集testcase類裡的單元測試函式

unittest.main()

單元測試 unittest

單元測試框架 unittest pytest uniittest unittest是python內建的單元測試框架,具有編寫用例,組織用例,執行用例,輸出測試報告等自動化框架的條件。unittest中的5個重要概念 test fixture,testcase,testsuite,testloder,...

Python單元測試unittest

python中有乙個自帶的單元測試框架是unittest模組,用它來做單元測試,它裡面封裝好了一些校驗返回的結果方法和一些用例執行前的初始化操作。在說unittest之前,先說幾個概念 testcase 也就是測試用例 testsuite 多個測試用例集合在一起,就是testsuite testlo...

Python單元測試unittest

python中有乙個自帶的單元測試框架是unittest模組,用它來做單元測試,它裡面封裝好了一些校驗返回的結果方法和一些用例執行前的初始化操作。在說unittest之前,先說幾個概念 testcase 也就是測試用例 testsuite 多個測試用例集合在一起,就是testsuite testlo...