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中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

Python 常用模块 re 使用方法详解

一.re模块的查找方法:   1.findall   匹配所有每一项都是列表中的一个元素 import re ret = re.findall('\d+','a...

Python中的Numeric包和Numarray包使用教程

要了解 Numerical Python 软件包的第一件事情是,Numerical Python 不会让您去做标准 Python 不能完成的任何工作。它只是让您 以快得多的速度去完成标准...

用C++封装MySQL的API的教程

其实相信每个和mysql打过交道的程序员都应该会尝试去封装一套mysql的接口,这一次的封装已经记不清是我第几次了,但是每一次我希望都能做的比上次更好,更容易使用。 先来说一下这次的封装...

Python全排列操作实例分析

本文实例讲述了Python全排列操作。分享给大家供大家参考,具体如下: step 1: 列表的全排列: 这个版本比较low # -*-coding:utf-8 -*- #!pytho...