python 單元測試與測試用例
#繼承unittest.TestCase類
#引入unittest 方法名以test開頭這樣才能在類執行時自動執行
#setUp()方法相當於一個共通方法.在執行其它測試方法時先執行此方法,把可以共用的屬性抽出來
例:
import unittest #引入測試基類
from survey import AnonymousSurvey #引入要測試的類
class TestAnonymousSurvey(unittest.TestCase): #繼承unittest的TestCase
def setUp(self):
question = "what language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English','Spanish','Mandarin']
def test_store_single_response(self):
'''測試單個答案會被妥善地儲存'''
self.my_survey.store_response(self.responses[0])
self.assertIn('English', self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()