Python單元測試unittest代碼詳解

來源:互聯網
上載者:User

Python單元測試unittest代碼詳解
前言

編寫函數或者類時,還可以為其編寫測試。通過測試,可確定代碼面對各種輸入都能夠按要求的那樣工作。本次我將介紹如何使用Python模組unittest中的工具來測試代碼。

測試函數

  首先我們先編寫一個簡單的函數,它接受姓、名、和中間名三個參數,並返回完整的姓名:

names.py

def get_fullname(firstname,lastname,middel=''):    '''建立全名'''    if middel:        full_name = firstname + ' ' + middel + ' ' + lastname        return full_name.title()    else:        full_name = firstname + ' ' + lastname        return full_name.title()

然後再目前的目錄下編寫調用函數程式

get_name.py

from names import get_fullnamemessage = "Please input 'q' to quit."print(message)while True:    first = input("Please input your firstname: ")    if first == 'q':        break    last = input("Please input your lastname: ")    if last == 'q':        break    middels = input("Please input your middel name or None: ")    if last == 'q':        break    formant_name = get_fullname(first,last,middels)    print("\tYour are fullname is: " + formant_name.title())

調用結果:

Please input 'q' to quit.Please input your firstname: xiaoPlease input your lastname: pengPlease input your middel or None:     Your are fullname is: Xiao PengPlease input your firstname: xiaoPlease input your lastname: pengPlease input your middel or None: you    Your are fullname is: Xiao You PengPlease input your firstname: q

進程已結束,結束代碼0

建立測試程式

  建立測試案例的文法需要一段時間才能習慣,但測試案例建立後,再針對函數的單元測試就很簡單了。先匯入模組unittest以及要測試的函數,再建立一個繼承函數unittest.TestCase的類,

並編寫一系列方法對函數行為的不同方便進行測試。

下面介紹測試上面names.py函數是否能夠正確的擷取姓名:

Test_get_name.py

import unittestfrom names import get_fullnameclass NamesTestCase(unittest.TestCase):    '''定義測試類別'''    def test_get_name2(self):        '''測試2個字的名字'''        formatied_name2 = get_fullname('xiao','pengyou')        self.assertEqual(formatied_name2,'Xiao Pengyou')    def test_get_name3(self):        '''測試3個字的名字'''        formatied_name3 = get_fullname('xiao','peng',middel='you')        self.assertEqual(formatied_name3,'Xiao Peng You')if __name__ == '__init__':    unittest.main()

測試結果:

Ran 2 tests in 0.034sOK

兩個測試單元測試通過測試!

在當前的大目錄下會產生一個測試報告,可以通過瀏覽器進行開啟查看。

由圖可知,兩個測試通過,並顯示測試的時間!!!

unittest.TestCase的各種斷言方法

unittest各種斷言方法
方      法 用      途
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中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.