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编程使用*解包和itertools.product()求笛卡尔积的方法

本文实例讲述了Python编程使用*解包和itertools.product()求笛卡尔积的方法。分享给大家供大家参考,具体如下: 【问题】 目前有一字符串s = "['a', 'b']...

python清除函数占用的内存方法

python升级到2.7.13 函数执行的结尾加上这个即可 for x in locals().keys(): del locals()[x] gc.collect() 原理是...

Python面向对象之类和对象实例详解

Python面向对象之类和对象实例详解

本文实例讲述了Python面向对象之类和对象。分享给大家供大家参考,具体如下: 类和对象(1) 对象是什么? 对象=属性(静态)+方法(动态); 属性一般是一个个变量;方法是一个个函数;...

Python创建数字列表的示例

【一】range()函数 在python中可以使用range()函数来产生一系列数字 for w in range(1,11): print(w) 输出: 1 2 3 4 5...

Python 实现「食行生鲜」签到领积分功能

Python 实现「食行生鲜」签到领积分功能

用过食行生鲜的同学应该知道,每天可以在食行生鲜签到,签到可以领到 20 积分,在购物时可以抵 2 毛钱。钱虽少,但是积少成多,买菜时可以抵扣一两块钱还是不错的。 今天我们就用 Pytho...