python3.6編寫的單元測試示例
本文實例講述了python3.6編寫的單元測試。分享給大家供大家參考,具體如下:
使用python3.6編寫一個單元測試demo,例如:對學生Student類編寫一個簡單的單元測試。
1、編寫Student類:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def get_grade(self):
if self.score >= 80 and self.score <= 100:
return 'A'
elif self.score >= 60 and self.score <= 79:
return 'B'
elif self.score >= 0 and self.score <= 59:
return 'C'
else:
raise ValueError('value is not between 0 and 100')
2、編寫一個測試類TestStudent,從unittest.TestCase繼承:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from student import Student
class TestStudent(unittest.TestCase):
def test_80_to_100(self):
s1 = Student('Bart',80)
s2 = Student('Lisa',100)
self.assertEqual(s1.get_grade(),'A')
self.assertEqual(s2.get_grade(),'A')
def test_60_to_80(self):
s1 = Student('Bart',60)
s2 = Student('Lisa',79)
self.assertEqual(s1.get_grade(),'B')
self.assertEqual(s2.get_grade(),'B')
def test_0_to_60(self):
s1 = Student('Bart',0)
s2 = Student('Lisa',59)
self.assertEqual(s1.get_grade(),'C')
self.assertEqual(s2.get_grade(),'C')
def test_invalid(self):
s1 = Student('Bart',-1)
s2 = Student('Lisa',101)
with self.assertRaises(ValueError):
s1.get_grade()
with self.assertRaises(ValueError):
s2.get_grade()
#運行單元測試
if __name__ == '__main__':
unittest.main()
3、運行結果如下:

4、行單元測試另一種方法:在命令行通過參數-m unittest直接運行單元測試,例如:python -m unittest student_test

最后對使用unittest模塊的一些總結:
- 編寫單元測試時,需要編寫一個測試類,從
unittest.TestCase繼承 - 對每一個類測試都需要編寫一個
test_xxx()方法 - 最常用的斷言就是
assertEqual() - 另一種重要的斷言就是期待拋出指定類型的Error,eg:
with self.assertRaises(KeyError): - 另一種方法是在命令行通過參數-m unittest直接運行單元測試:eg:
python -m unittest student_test - 最簡單的運行方式是xx.py的最后加上兩行代碼:
if __name__ == '__main__': unittest.main()
更多Python相關內容感興趣的讀者可查看本站專題:《Python入門與進階經典教程》、《Python字符串操作技巧匯總》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python 多模式字符串搜索 Aho-Corasick詳解
Aho-Corasick 算法是一種用于精確或近似多模式字符串搜索的高效算法,本文給大家介紹Python 多模式字符串搜索 Aho-Corasick的相關知識,感興趣的朋友跟隨小編一起看看吧2025-01-01
使用grappelli為django admin后臺添加模板
本文介紹了一款非常流行的Django模板系統(tǒng)--grappelli,以及如何給Django的admin后臺添加模板,非常的實用,這里推薦給大家。2014-11-11
pytorch + visdom CNN處理自建圖片數據集的方法
這篇文章主要介紹了pytorch + visdom CNN處理自建圖片數據集的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06

