python的unittest测试类代码实例

yipeiwu_com6年前Python基础

nittest单元测试框架不仅可以适用于单元测试,还可以适用WEB自动化测试用例的开发与执行,该测试框架可组织执行测试用例,并且提供了丰富的断言方法,判断测试用例是否通过,最终生成测试结果。今天笔者就总结下如何使用unittest单元测试框架来进行WEB自动化测试。

题目:

编写一个名为Employee的类,其方法__init__()接受名、姓和年薪,并将它们都存储在属性中。编写一个名为give_raise()的方法,它默认将年薪增加5000美元,但也能够接受其他的年薪增加量。

为Employee编写一个测试用例,其中包含两个测试方法:test_give_default_raise()和test_give_custom_raise()。使用方法setUp(),以免在每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。

employ.py 
待测试的类 
 class Employee(): 
  def __init__(self,first_name,last_name,salary): 
    self.first_name=first_name 
    self.last_name=last_name 
    self.salary=salary 
  def give_raise(self,default=5000): 
    return int(self.salary)+default 
test_employ.py 
测试类  
# coding=utf-8 
import unittest 
from employ import Employee  
class TestEmploy(unittest.TestCase): 
  def setUp(self): 
    self.people=Employee("ZHU","Fangya",20000) 
    self.salary=[25000,30000] 
  def test_give_default_raise(self): 
    self.assertEqual(self.people.give_raise(),self.salary[0])  
  def test_give_custome_raise(self): 
    self.default=10000 
    self.assertEqual(self.people.give_raise(default=10000),self.salary[1])   
if __name__=="__main__": 
  unittest.main() 

运行结果

Done:2 of 2 (0.137s) 
C:\Python27\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 4.0.6\helpers\pycharm\utrunner.py" C:\Users\waiwai\PycharmProjects\untitled2\test_employ.py true 
Testing started at 16:03 ... 
 
Process finished with exit code 0 

总结

以上就是本文关于python的unittest测试类代码实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python字典排序实例详解

本文实例分析了python字典排序的方法。分享给大家供大家参考。具体如下: 1、 准备知识: 在python里,字典dictionary是内置的数据类型,是个无序的存储结构,每一元素是k...

利用python读取YUV文件 转RGB 8bit/10bit通用

注:本文所指的YUV均为YUV420中的I420格式(最常见的一种),其他格式不能用以下的代码。 位深为8bit时,每个像素占用1字节,对应文件指针的fp.read(1); 位深为10b...

详解Django 时间与时区设置问题

再写入数据库对时间进行加减操作时候 django报告了错误 TypeError: can't subtract offset-naive and offset-aware datet...

Python中datetime模块参考手册

前言 Python提供了多个内置模块用于操作日期时间,像 calendar,time,datetime。time模块提供的接口与C标准库 time.h 基本一致。相比于 time 模块,...

python获取当前目录路径和上级路径的实例

在使用python的时候总会遇到路径切换的使用情况,如想从文件夹test下的test.py调用data文件夹下的data.txt文件: . └── folder ├── data...