脚本专栏 发布日期:2025/11/4 浏览次数:1
本文实例讲述了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()with self.assertRaises(KeyError):python -m unittest student_testif __name__ == '__main__': unittest.main()
更多Python相关内容感兴趣的读者可查看本站专题:《Python入门与进阶经典教程》、《Python字符串操作技巧汇总》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。