今天开始针对类开展测试
unittest模块中的6中断言方法:
assertEqual(a,b) 核实 a == b
assertNotEqual(a,b) 核实a != b
assertTrue(x) 核实 x 为
True assertFalse(x) 核实x为False
assertIn(item,list)核实item 在list中
assertNotIn(ltem,list)核实item不在list中
Method Use
assertEqual(a, b) Verify that a == b
assertNotEqual(a, b) Verify that a != b
assertTrue(x) Verify that x is True
assertFalse(x) Verify that x is False
assertIn(item, list) Verify that item is in list
assertNotIn(item, list) Verify that item is not in list
编写一个要测试的类,下面是要收集一个针对一个问题的匿名答案
匿名回答:anonymous answer
问卷:survey question
用了4个函数来实现
存储问卷,展示问卷,存储匿名答案,展示匿名答案
class AnonymousSurvey:
#Collect anonymous answers to a survey question
def __init__(self, question):
#Store a question, and prepare to store responses.
self.question = question
self.responses = []
def show_question(self):
#Show the survey question
print(self.question)
def store_response(self,new_response):
#Store a single response to the survey
self.responses.append(new_response)
def show_results(self):
#Show all the responses that have been given
print("Survey results:")
for response in self.responses:
print(f"- {response}")
from test import AnonymousSurvey
#定义一个问题,并创建一个调查。
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
#显示问题并存储答案
my_survey.show_question()
print("Enter 'q' at any time to quit. \n")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
# 显示调查结果
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
X:\Python\Python38\python.exe X:\python_work\homework.py
What language did you first learn to speak?
Enter 'q' at any time to quit.
Language: chinese
Language: english
Language: japanese
Language: q
Thank you to everyone who participated in the survey!
Survey results:
- chinese
- english
- japanese
Process finished with exit code 0
下面编写测试,对AnonymousSurvey类的行为进行验证:如果用户面对调查问题只提供一个答案,这个答案也能被妥善地存储
将在这个答案被存储后,使用方法assertIn()
import unittest
from test import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
#针对AnonymousSurvey类的测试
def test_store_single_response(self):
#测试单个答案被妥善地存储
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English',my_survey.responses)
if __name__ == '__main__':
unittest.main()
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
[Finished in 141ms]
首先导入模块unittest 和要测试的类AnonymousSurvey,将测试用例命名为TestAnonymousServey,它也继承了unittest.TestCase。
第一个测试方法验证:调查问题的单个答案被存储后,会包含在调查结果列表中。
所以用了single的描述名称
要测试类的行为,就需要创建其实例,使用问题question = “What language did you first learn to speak?”
然后一个名为my_survey的实例,接下来使用方法store_response存储答案English。
接下来检查English是否包含在列表my_survey.responses
接下来核实当用户提供三个答案时,它们也被妥善处理