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)

请按任意键继续. . .
相关推荐
fanruitian5 小时前
python 装饰器 闭包
python
Fnetlink15 小时前
Fnet 云网安 261023
运维·开发语言·网络·人工智能·安全·web安全·php
泡茶喝茶写代码5 小时前
A股量化策略回测实战:从行情数据到绩效评估(第 13 篇):放量突破策略
java·python·股票数据api·股票数据api接口·股票量化数据api·股票量化数据接口
ESDWAN6 小时前
SD-WAN 主备切换为什么仍会断网?从检测、切换到会话恢复分析
运维·开发语言·网络·php
jimy16 小时前
lvalue、xvalue、prvalue(二):引用是哪一类?
开发语言·c++·1024程序员节
cxyxixiy6 小时前
数智码力:数据核对不用人工比对,Python 快速完成多表格差异校验
开发语言·python·学习
一个风轻云淡6 小时前
从 int $0x80 到 iret:用 gdb 把 getpid 走一遍
linux·c语言·开发语言·汇编
LMT流氓兔6 小时前
第五单元——第11课:自动测试“拒绝后绝不能写入”
数据库·人工智能·python·langchain
杜 硕6 小时前
从零开始的C++生活——第三讲
开发语言·c++·生活
tianbin9116 小时前
批处理与微调辅助场景:Claude 中转并发、链路缓存与压测对比
java·开发语言·缓存