1.各种断言方法
常用断言方法:
方法 |
用途 |
assertEqual(a, b) |
核实a == b |
assertNotEqual(a, b) |
核实a != b |
assertTrue(x) |
核实x为True |
assertFalse(x) |
核实x为False |
asseertIn(item, list) |
核实item在list中 |
assertNotIn(item, list) |
核实item不在list中 |
2.一个要测试的类
首先编写一个类:
survey.py
class AnonymousSurvey: """收集匿名调查问卷的答案""" def __init__(self, question): """存储一个问题,并为存储答案做准备""" self.question = question self.responses = [] def show_quetion(self): """显示调查问卷""" print(self.question) def store_response(self, new_response): """存储单份调查答案""" self.responses.append(new_response) def show_result(self): """显示收集到的所有答卷""" print("Survey result:") for response in self.responses: print('- ' + response)
为证明AnonymousSurvey类可以正确的工作,编写一个使用它的程序:
language_survey.py
from survey import AnonymousSurvey # 定义一个问题,并创建一个表示调查的AnonymousSurvey对象 question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) # 显示并存储问题的答案 my_survey.show_quetion() 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 survey!") my_survey.show_result()
运行结果:
What language did you first learn to speak? Enter 'q' at any time to quit. Language: English Language: Spanish Language: English Language: Mandarin Language: q Thank you to everyone who participated in survey! Survey result: - English - Spanish - English - Mandarin
3.测试AnonymousSurvey类
对AnonymousSurvey类行为的一个方面进行验证:如果用户面对调查问题时只提供了一个答案,这个答案也能被妥善地存储。使用方法assertIn()来核实它包含在答案列表中:
test_survey.py
import unittest from survey 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()
运行test_survey.py时,测试通过了:
Ran 1 test in 0.010s OK
只能收集一个答案的调查用途不大。下面核实用户提供三个答案时,它们也将被妥善地存储。为此,在AnonymousSurvey中再添加一个方法:
import unittest from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase): """针对AnonymousSurvey类的测试""" def test_store_single_response(self): ... def test_store_three_response(self): """测试三个答案会被妥善地存储""" question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) responses = ['English', 'Spanish', 'Mandarin'] for response in responses: my_survey.store_response(response) for response in responses: self.assertIn(response, my_survey.responses) if __name__ == "__main__": unittest.main()
再次运行test_survey.py时,两个测试都通过了:
Ran 2 te