python测试类

待测试的类survey.py

python 复制代码
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)

用于测试的类

python 复制代码
import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
	
	def test_store_single_response(self):
		'''测试一个答案也会被妥善储存'''
		question="What language did you first learn to speak?"
		#survey的属性question
		my_survey=AnonymousSurvey(question)
		#形成实例my_survey
		my_survey.store_response('english')
		#实例.方法名(形参)调用方法
		
		self.assertIn('english',my_survey.responses)
		#断言进行匹配
		
		
	def test_store_three_responses(self):
		question="what language did you learn first?"
		#survey的属性
		my_survey=AnonymousSurvey(question)
		#形成实例
		responses=['english','spanish','mandarin']
		#survey的另一个属性,一个不为空的测试用列表
		for response in responses:
			my_survey.store_response(response)
		#对测试列表中的每个元素调用survey中的方法store_response(元素)
		#调用后应该形成了一个试后列表
			
		for response in responses:
			self.assertIn(response,my_survey.responses)
		#对测试列表中的每个元素进行循环,检测它们是否在试后列表中
		#my_survey.responses就是前面survey中的self.responses
			
unittest.main()

输出

python 复制代码
..
----------------------------------------------------------------------
Ran 2 tests in 0.004s

OK


------------------
(program exited with code: 0)

请按任意键继续. . .
相关推荐
李可以量化2 分钟前
Redis Client 从了解到精通(二)下:String 类型进阶操作全解
redis·git·python·量化交易·qmt
wy3136228212 分钟前
Git——ignore让项目的 target 目录真正被忽略(忽略其他文件也是同样的道理)
开发语言·git
格林威2 分钟前
C#图像分块处理:图像按行或按块(Tile)切分,多个 CPU 核心同时处理不同的区域
开发语言·图像处理·人工智能·机器学习·计算机视觉·c#·工业相机
leisoo809710 分钟前
财报舞弊预警系统实战用Python挖掘应收存货异常因子 IG50免费开源股票数据API接口
开发语言·python
君顾111 分钟前
AI新零售线上商城系统实战:架构设计与开发全流程指南
java·开发语言·零售
wind1003217 分钟前
Outdated Visual C++ Redistributable 过时 VC++ 运行库报错修复
开发语言·c++
吾皇斯巴达23 分钟前
O_DIRECT与gcsfuse的go程序中实现内存页面对齐
开发语言·后端·golang
光电的一只菜鸡40 分钟前
高通tuning中eis需要调什么
java·开发语言·前端
兔兔兔兔141 分钟前
记录C++ 12
开发语言·c++
cui_ruicheng1 小时前
LangChain 应用开发(十二):Agent 中间件与内置中间件
人工智能·python·中间件·langchain