Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: 也就是說, 將一般的軟體開發流程分成很多小的開發 cycle 並一直重覆
其做法如下:
軟體開發人員撰寫 一個自動測試案例其定義一個新的函式, 然後再產生測試案例的最少量的程式碼,而那些程式碼可以通過那些測試並且可再分解( refactors ) 那些可被接受測試標準的程式碼.
Basically , TDD 的精神式與extreme programming 中 "測試為優先" 的概念; 同時 , programmers 也可以此概念改善及除錯舊有的程式碼.
Kent Becker is the creator of TDD and he depends on the rhythm of test-driven development to develop it.
Basically , the rhythm as below: ( From book " Test Driven Development by Example " )
1. Quickly add a test ( 趕快加一個測試 )
2. Run all tests and see the new one fail ( 執行所有的測試並看看新加的那個測試案例是否失敗)
3. Make a little change ( 如果失敗的話就做小小的改變)
4. Run all tests and see them all succeed ( 執行所有的測試並看全部測試案例成功)
5. Refactor to remove duplication (再分解程式碼去除重複的部分)
The followings are the details of steps of TDD
- Add a test ( 加一個測試 )
In test-driven development, 每個新的功能起於一個測試案例的撰寫, 這是TDD的宗旨.所以軟體功能尚未完成前就先寫測試案例的driver,所必然會有errors, 原因很簡單, driver 目的是在測試 implement of unit . 如果這測試會過就可能的原因是新功能已經加入,或是該測試已經失敗了. 所以對任programmers來說, 對規格一定必須要清楚了解. 這個目的是要developers 反覆的了解規格, this is a very important for a good software development team.
![]() |
| TDD flow from Wiki |
- Run all tests and see if the new one fails ( 執行所有的測試並且看若新加的那個測試案例失敗)
TDD的精神是先寫測試驅動,用測試驅動去測試系統的功能是否正確無誤, 當你每寫一個測試案例時,就應該寫測試一下,反覆此動作一直到所有測試案例都pass為止, 所以當每加一個測試案例時,如果測試驅動測試之後有沒過的,就是必須檢查測試驅動是否有寫錯,或是功能未完成.
- Write some code ( 寫一些碼 )
如上如果測試驅動將系統中的未完成的功能測試出來, 此時就是必須寫一些程式碼來完成它們.
Run the automated tests and see them succeed (執行自動測試並且看看他們成功)
TDD 所加入的測試驅動通常都是與unit test framework 所結合的, 故所有的測試案例都可被執行為自動測試案例 , 如上的步驟如果寫一些碼, 但需要測試其碼的robustness, 此stage可以完成.當所有的測試案例都自動化且通過測試時,programmers 就有信心說此系統已符合系統需求.
- Refactor code (再分解程式碼)
既然程式碼已經通過所有的測試案例也意味了programmers了解requirements及達到客戶的需求,最後再針對整個程式碼最調整,其目的是將程式架構作最佳化, 找出程式可再精簡的部分.

No comments:
Post a Comment