選擇性的Unit testing - 從cost和benefit的角度 (2)

Selective Unit Testing – Costs and Benefits
http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/

對程式進行unit test要花費多少cost?

基本上有幾件事情明顯地會有cost:

1. 實際撰寫unit test的時間
2. 修改和更新unit test的時間: 可能是refactoring測試程式的時間, 或者修改非預期的有錯誤的測試
3. 因為害怕refactor 程式碼會導致之前的unit test失敗, 因此產生更多額外的工作

但是根據作者的經驗, unit test的cost是跟受測程式的dependency有關. dependency(concrete or interface)的個數越多, cost就越高

即使你有用IoC(Inversion of Control) container 或是採用interface programming也是會同樣的結果


成本和效益的視覺化

我們根據unit test的cost和unit test 的benefit, 可以將程式分成這四類

1. Complex code with few dependencies (top left)
- 通常這類都是self-contained的algorithm, 像是sort or parse data.
- 它很適合使用unit test, 因為他很容易使用unit test來進行, 並且效果非常明顯

2. Trivial code with many dependencies (bottom right)
- 它是屬於coordinators, 用來整合大家, 讓大家可以交互作用.
- 非常不適合使用unit test來驗證, 代價高效果低.
- 你的時間是很有限的, 考慮花在地方

3. Complex code with many dependencies (top right)
- 要寫unit test的代價很高, 但是不寫的risk也很高
- 通常你會把拆解成兩個部分來處理:
  * the complex logic (algorithm)
  * the bit that interacts with many dependencies (coordinator).
  ==> 這時候你就可以知道要怎麼辦
 
4. Trival code with few dependencies (bottom left)
- 通常我們不用擔心這個部份


基本上, 作者希望大家不要誤解他, 他並不是說你不應該做單元測試或是TDD, 他想強調的是:
1. 他希望能夠花時間在真正有high business value的程式碼上面, 所以algorithms or self-contained business logic是他注意的重點

2. 他有時候會故意把受測程式分出algorithms和coordinators, 因此前者可以讓他努力去做測試

3. 他發現到有些實務上的business value的部份需要利用integration testing來驗證. 因此會藉助Selenium RC or WatiN來輔助測試工作的進行. 這並不是用來要取代unit test. 他只是認為花時間來從whole system的角度來看系統是否運作正常, 會比用unit test來驗證"Trivial code with many dependencies"和"Trival code with few dependencies"這兩部份有意義


arrow
arrow
    全站熱搜

    kojenchieh 發表在 痞客邦 留言(0) 人氣()