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)

请按任意键继续. . .
相关推荐
Sammyyyyy8 分钟前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
站大爷IP15 分钟前
Python与MySQL:从基础操作到实战技巧的完整指南
python
老歌老听老掉牙19 分钟前
SymPy 矩阵到 NumPy 数组的全面转换指南
python·线性代数·矩阵·numpy·sympy
站大爷IP24 分钟前
Python条件判断:从基础到进阶的实用指南
python
赛博郎中29 分钟前
pygame小游戏飞机大战_8继承精灵玩家优化
python·pygame
William一直在路上41 分钟前
Python数据类型转换详解:从基础到实践
开发语言·python
看到我,请让我去学习1 小时前
Qt— 布局综合项目(Splitter,Stacked,Dock)
开发语言·qt
GUET_一路向前2 小时前
【C语言防御性编程】if条件常量在前,变量在后
c语言·开发语言·if-else·防御性编程
曳渔2 小时前
UDP/TCP套接字编程简单实战指南
java·开发语言·网络·网络协议·tcp/ip·udp
trayvontang2 小时前
Python虚拟环境与包管理工具(uv、Conda)
python·conda·uv·虚拟环境·miniconda·miniforge