Python单元测试框架unittest简明使用实例

yipeiwu_com6年前Python基础

测试步骤
1. 导入unittest模块
import unittest

2. 编写测试的类继承unittest.TestCase
class Tester(unittest.TestCase)

3. 编写测试的方法必须以test开头
def test_add(self)
def test_sub(self)

4.使用TestCase class提供的方法测试功能点

5.调用unittest.main()方法运行所有以test开头的方法

复制代码 代码如下:

if __name__ == '__main__':
unittest.main()

实例如下
被测试类

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8

class Computer(object):
 @staticmethod
 def add(a, b):
  return a + b;
 
 @staticmethod
 def sub(a, b):
  return a - b;<strong> </strong>

测试类

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8
import unittest
from Testee import Computer

class Tester(unittest.TestCase): 
 def test_add(self):
  self.assertEqual(Computer.add(2, 3), 5, "test add function")
  
 def test_sub(self):
  self.assertEqual(Computer.sub(5, 1), 4, "test sub function") 

if __name__ == '__main__':
  unittest.main()

​运行结果:

复制代码 代码如下:

----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK

相关文章

Python异步操作MySQL示例【使用aiomysql】

本文实例讲述了Python异步操作MySQL。分享给大家供大家参考,具体如下: 安装aiomysql 依赖 Python3.4+ asyncio PyMySQL 安装...

Python 字典(Dictionary)操作详解

Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。 一、创建字典 字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:...

python调用百度语音识别api

python调用百度语音识别api

最近在处理语音检索相关的事。 其中用到语音识别,调用的是讯飞与百度的api,前者使用js是实现,后者用python3实现(因为自己使用python) 环境: python3.5 ce...

详解python:time模块用法

详解python:time模块用法

time模块下有两种时间表示方法: 第1种是:时间戳的方式。是基于1970年1月1日0时0分0秒的偏移。浮点数。 第2种是:struct_time()类型的表示方法。gmtime()和l...

Python实现数据结构线性链表(单链表)算法示例

Python实现数据结构线性链表(单链表)算法示例

本文实例讲述了Python实现数据结构线性链表(单链表)算法。分享给大家供大家参考,具体如下: 初学python,拿数据结构中的线性链表存储结构练练手,理论比较简单,直接上代码。 #...