前言:

编写函数或者类时,需要编写测试代码,来保证其的功能运行是否按预期的那样工作。在程序添加新的代码时,用来测试是否会破坏本身的功能。

我们使用python自带的unittest模块来测试代码。

编写函数:

def get_formatted_name(first,last,middle=''):
"""生成整洁的姓名"""
if middle:
full_name = first + ' '+ middle +' '+ last
else:
full_name = first + ' ' + last
return full_name.title()

编写测试:

import unittest
from name_function import get_formatted_name class NameTestCase(unittest.TestCase):
"""测试name_function.py """
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin') def test_first_last_middle_name(self):
"""能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
formatted_name = get_formatted_name('wolfgang','mozart','amadeus')
self.assertEqual(formatted_name,'Wolfgang Amadeus Mozart') unittest.main()

编写类:

class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self, question):
"""存储一个问题,并为存储答案做准备"""
self.question = question
self.responses = [] def show_question(self):
"""显示调查问卷"""
print(self.question) def store_response(self, new_response):
"""存储单份调查答卷"""
self.responses.append(new_response) def show_results(self):
"""显示收集到的所有答卷"""
print("Survey results")
for response in self.responses:
print('- '+ response)

编写测试:

import unittest
from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
lists = ['English','China','Japanese']
for s in lists:
my_survey.store_response(s)
self.assertIn(s, my_survey.responses) unittest.main()

总结:

unittest模块不仅支持单元测试,在接口和功能测试也能直接套用其中的方法。编写unittest必须添加继承unittest.TestCase类,测试的函数必须以test*开头,以及使用unittest.mian方法来运行此测试模块。

最新文章

  1. 在Linux和Windows的Docker容器中运行ASP.NET Core
  2. MongoDB基础知识
  3. 【转】Android之自定义Adapter的ListView
  4. SQL Server 内存数据库原理解析
  5. virtualenv -- python虚拟沙盒(linux版本)
  6. iptables常用命令
  7. C# RAS 非对称加密类 支持长字符串
  8. lsof-列出当前系统打开文件
  9. 基于三星ARM9(S3C2410)的交通违章抓拍系统的开发
  10. Java命令模式以及来自lambda的优化
  11. input选择框样式修改与自定义
  12. <p>标签样式设置
  13. SharePoint 2010 之soap:Server服务器无法处理请求
  14. [PHP]实体类基类和序列化__sleep问题
  15. Unit 3.标签的分类和嵌套规则
  16. spring4笔记----spring4构造注入
  17. centos7-软件安装-mysql5.7
  18. redis集群redis-cloud搭建
  19. 【Pyton】【小甲鱼】爬虫
  20. CF 827E Rusty String FFT

热门文章

  1. js根据ip地址获取城市地理位置
  2. Redis---03Redis事务
  3. 跟我一起学.NetCore之MediatR好像有点火
  4. 1,web项目工作流程
  5. RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
  6. Odoo环境搭建之问题readme
  7. Centos8防火墙设置
  8. 记elementUI一个大坑
  9. Java 中数组转换为 List
  10. 手把手教你使用Vuex(二)