Python unittest學習筆記

2021-10-19 05:11:10 字數 1821 閱讀 3673

python標準庫中的模組unittest提供了**測試工具。

單元測試用於核實函式的某個方面沒問題

測試用例是一組單元測試,這些單元測試一起核實函式在各種情形下的行為都符合要求。

良好的測試用例考慮到了函式可能收到的各種輸入,包含針對所有這些情形的測試。

全覆蓋式測試用例包含一整套單元測試,涵蓋了各種可能的函式使用方式。

只能在繼承unittest.testcase類中使用如下6個常用的斷言方法

assertequal(a, b)             --- 核實 a==b

assertnotequal(a, b)       --- 核實 a!=b

asserttrue(x)                   --- 核實 x為true

assertfalse(x)                 --- 核實 x為false

assertin(item, list)            --- 核實 item在list

assertnotin(item, list)      --- 核實 item不在list

應用程式

class employee:

def __init__(self, first_name, last_name, salary):

self.first_name = first_name

self.last_name = last_name

self.salary = salary

def give_raise(self, great=50000):

self.salary += great

print(f"the salary of is ")

# ****** test

"""jack = employee('li', 'kai', 500000)

jack.give_raise(100000)

print(jack.salary)"""

測試

import unittest

from employee import employee

class testemployee(unittest.testcase):

"""test employee.py"""

def setup(self):

self.san = employee('san', 'zhang', 100000)

self.great = 60000

def test_give_default_raise(self):

self.san.give_raise()

self.assertequal(self.san.salary, 150000)

def test_give_custom_raise(self):

self.san.give_raise(self.great)

self.assertequal(self.san.salary, 160000)

if __name__ == '__main__':

unittest.main()

執行測試結果

python unittest 之mock學習筆記

mock的詳細用法 英文介紹 本文先對函式的mock方法進行演示。假設有檔案fun1和fun2,fun2中的函式呼叫了fun1中的函式。利用mock方法生成fun1中函式的乙個fake返回值,在此基礎上,對fun2中的函式進行單元測試。如下 fun1檔案 usr bin env python cod...

python unittest基礎用法

unittest 執行例項 基礎用法 import unittest 匯入unittest模組 defcalc a,b 被測的方法 return a b class testcale unittest.testcase 必須要整合unittest的testcase方法 deftest1 self r...

python unittest測試框架介紹

介面測試隨著測試用例變多,需要構建測試用例和測試集合,就需要測試框架來完成這些工作。unittest自帶的測試框架。單個檔案測試 test 001.py import unittest class test unittest.testcase def setup self print setup d...