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)

请按任意键继续. . .
相关推荐
2739920291 分钟前
生成二维码 QRCode (QT)
开发语言·qt
火山灿火山12 分钟前
初识Qt(使用不同中方式创建helloworld)
开发语言·qt
BD_Marathon40 分钟前
sbt 编译打包 scala
开发语言·后端·scala
雾岛听蓝1 小时前
C++ 入门核心知识点(从 C 过渡到 C++ 基础)
开发语言·c++·经验分享·visual studio
studytosky1 小时前
深度学习理论与实战:MNIST 手写数字分类实战
人工智能·pytorch·python·深度学习·机器学习·分类·matplotlib
7***37451 小时前
Java设计模式之工厂
java·开发语言·设计模式
上不如老下不如小1 小时前
2025年第七届全国高校计算机能力挑战赛初赛 Python组 编程题汇总
开发语言·python·算法
Q_Q5110082851 小时前
python+django/flask的结合人脸识别和实名认证的校园论坛系统
spring boot·python·django·flask·node.js·php
Q_Q5110082852 小时前
python+django/flask的选课系统与课程评价整合系统
spring boot·python·django·flask·node.js·php
程序员小白条2 小时前
你面试时吹过最大的牛是什么?
java·开发语言·数据库·阿里云·面试·职场和发展·毕设