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)

请按任意键继续. . .
相关推荐
纪念 2295 小时前
c++ string(二)
开发语言·c++
SimonKing5 小时前
零大模型依赖!SQLite FTS5 + jieba 打造纯本地知识库搜索
后端·python·程序员
慢云智慧空间5 小时前
从智能终端到空间AI,慢云科技如何重新定义智慧人居?
人工智能·python·科技
李福春5 小时前
斗破Google ADK Java苍穹-第5境斗灵-凝物通脉-Context与State
java·开发语言·人工智能·java-ee·google adk·深圳同盟·腾讯云架构师技术同盟
十年Java程序媛5 小时前
Java 接口和抽象类对比|抛弃老旧八股,正确选型
java·开发语言·spring boot·后端
见叶之秋5 小时前
【C++】从基类到派生类:关于C++继承的务实梳理
开发语言·c++
yi0115 小时前
LeetCode 3. 无重复字符的最长子串|不定长滑动窗口:什么时候更新最大值?
笔记·python·算法·leetcode·双指针·滑动窗口
kyle~5 小时前
C++ 智能指针:RAII、所有权与对象生命周期
开发语言·c++
y1su5 小时前
Leetcode 单调栈模板
java·开发语言·数据结构·算法·leetcode
2601_962885725 小时前
如何用 Python 计算索提诺比率和卡玛比率?
开发语言·python