待辦清單#
Invoke test methodInvoke setUp firstInvoke tearDown afterward- Invoke tearDown even if the test method fails
- Run multiple tests
Report collected resultsLog string in WasRun- Report failed tests
從小規模測試開始#
我們寫一個更細粒度的測試,確保在記下失敗測試後能正確印出結果:
def testFailedResultFormatting(self):
result= TestResult()
result.testStarted()
result.testFailed()
assert("1 run, 1 failed" == result.summary())testStarted() 和 testFailed() 是我們期望在測試開始和測試失敗時分別傳送給 result 的訊息。如果在以這個順序發送這些訊息後 summary 能正確印出,那麼程式問題就簡化為:如何讓這些訊息被正確發送。一旦它們被發送,整體就會運作。
實作失敗計數#
實作方式是維護一個失敗計數:
def __init__(self):
self.runCount= 0
self.errorCount= 0
def testFailed(self):
self.errorCount= self.errorCount + 1計數正確後,就能正確印出:
def summary(self):
return "%d run, %d failed" % (self.runCount, self.failureCount)捕捉例外#
現在預期只要正確呼叫 testFailed(),就會得到預期結果。何時呼叫?在捕捉到 test method 的例外時:
def run(self):
result= TestResult()
result.testStarted()
self.setUp()
try:
method = getattr(self, self.name)
method()
except:
result.testFailed()
self.tearDown()
return result注意: 這個方法中隱藏了一個微妙之處。以目前的寫法,如果在
setUp()期間發生災難,例外不會被捕捉。這不可能是我們的本意——我們希望測試彼此獨立執行。然而,在修改程式碼之前需要另一個測試。作者將這個測試及其實作留作練習。
待辦清單更新:
Invoke test methodInvoke setUp firstInvoke tearDown afterward- Invoke tearDown even if the test method fails
- Run multiple tests
Report collected resultsLog string in WasRunReport failed tests- Catch and report setUp errors
本章回顧#
- 讓小規模測試先運作
- 重新引入大規模測試
- 利用小測試所展示的機制,快速讓大測試通過
- 注意到一個潛在問題,將其記錄到待辦清單,而非立即處理