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)

请按任意键继续. . .
相关推荐
小陈工几秒前
Python Web开发入门(三):配置文件管理与环境变量最佳实践
开发语言·jvm·数据库·python·oracle·性能优化·开源
cch89183 分钟前
PHP vs Java:主流编程语言深度对比
java·开发语言·php
少司府5 分钟前
C++基础入门:类和对象(上)
c语言·开发语言·c++·类和对象·访问限定符
deep_drink6 分钟前
1.1、Python 与编程基础:开发环境、基础工具与第一个 Python 项目
开发语言·人工智能·python·llm
丸辣,我代码炸了11 分钟前
如何手搓序列化器(以java为例)
java·开发语言·kafka
快乐柠檬不快乐13 分钟前
基于Java+SpringBoot+SSM攻防靶场实验室平台
java·开发语言·spring boot
lly20240614 分钟前
SQL AND & OR 操作符详解
开发语言
伐尘14 分钟前
【图形学】CS:GO 的 “Uber 着色器” 是啥?
开发语言·golang·着色器
Elnaij19 分钟前
从C++开始的编程生活(25)——C++11标准Ⅱ
开发语言·c++
杨超越luckly19 分钟前
HTML应用指南:利用GET请求获取中国生活垃圾焚烧发电厂位置信息
python·arcgis·html·数据可视化·生活垃圾焚烧发电厂