python3.6编写的单元测试示例

yipeiwu_com6年前Python基础

本文实例讲述了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模块的一些总结:

  1. 编写单元测试时,需要编写一个测试类,从unittest.TestCase继承
  2. 对每一个类测试都需要编写一个test_xxx()方法
  3. 最常用的断言就是assertEqual()
  4. 另一种重要的断言就是期待抛出指定类型的Error,eg:with self.assertRaises(KeyError):
  5. 另一种方法是在命令行通过参数-m unittest直接运行单元测试:eg:python -m unittest student_test
  6. 最简单的运行方式是xx.py的最后加上两行代码:
if __name__ == '__main__':
  unittest.main()

更多Python相关内容感兴趣的读者可查看本站专题:《Python入门与进阶经典教程》、《Python字符串操作技巧汇总》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

介绍Python的Urllib库的一些高级用法

介绍Python的Urllib库的一些高级用法

1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性。 首先,...

对python中的try、except、finally 执行顺序详解

如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to r...

DJANGO-URL反向解析REVERSE实例讲解

DJANGO-URL反向解析REVERSE实例讲解

解决path中带参数的路径。 reverse(viewname,urlconf=None,args=None,Kwargs=None,current_app=None) book/vie...

tensorflow实现逻辑回归模型

逻辑回归模型 逻辑回归是应用非常广泛的一个分类机器学习算法,它将数据拟合到一个logit函数(或者叫做logistic函数)中,从而能够完成对事件发生的概率进行预测。 impo...

详解python statistics模块及函数用法

本节介绍 Python 中的另一个常用模块 —— statistics模块,该模块提供了用于计算数字数据的数理统计量的函数。它包含了很多函数,具体如下表:...