类的测试与函数的测试相似
测试函数的案例:https://blog.csdn.net/hanhanwanghaha/article/details/107487037
survey.py
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("Servey results: ")
for response in self.responses:
print('favorite sport: ' + response)
为证明AnonymousSurvey能够正确地工作,编写一个使用他的程序
sports_survey
from survey import AnonymousSurvey
# 定义一个问题,并创建dac一个表示调查的AnonymousSurvey对象
question = "What's your favorite sport ?"
my_survey = AnonymousSurvey(question)
# 显示问题并储存答案
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
response = input("Sports:")
if response == 'q':
break
my_survey.store_response(response)
# 显示调查结果
print("\nThank you for your participation in this survey!")
my_survey.show_results()
创建测试的时候有个小技巧:
1.点击New,再点击Python File之后
2.直接点击Python unit test,随后点击Enter会帮我们自动生成一个单元测试框架
测试AnonymousSurvey类:这里用到了Setup方法创建一个调查对象和一组答案,供方法test_store_single_response()和test_store_three_responses()使用
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def setUp(self):
"""创建一个调查对象和一组答案,供使用的测试方法使用"""
question = "What's your favorite sport ?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['sleep', 'reading', 'running']
def test_store_single_response(self):
"""测试单个答案是否会被妥善储存"""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""测试3个答案是否会被妥善储存"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if __name__ == '__main__':
unittest.main()
如果在TestCase类中包含方法setUp(),python将先运行它,再运行各个以test_开头的方法。