Mocks Aren't Stubs 閱讀心得 Lu Wei Jen http://blog.weijen.net http://twitter.com/weijenlu http://facebook.com/weijenlu
文章網址 http://martinfowler.com/articles/mocksArentStubs.html
都是因為跟 ihower 晚上不睡覺害的 發現自己對 Mock & Stub  的觀念不清楚
先看個程式 沒有 mock object 的測試 v.s. 有 mock object 的測試
focus on one element you want
可是世界沒有這麼單純
這時你有兩個選擇 實際製作有互動到的物件
製造假的物件,讓互動完成
造假有兩種  Mocks v.s Stubs
Mock Mock object
Stub Real object  Stub method
Stubs is State Verification 結果對,就對
Mocks is Behavior Verification 不只要結果正確,你平常還得行的正,坐的端
class MailServer def initialize @messages = Array.new end def send(msg) @messages << msg end def number_sent @message.size() end end A Simple Stub
A Simple Stub Test it &quot;如果庫存不足,要寄信通知&quot; do order = Order.new(&quot;海尼根&quot;, 51) mailer = MailServer.new order.set_mailer(mailer) order.fill(warehouse) mailer.number_sent.should eql(1) end
A Simple Mock Test it &quot; 如果庫存不足,要寄信通知 &quot; do order = Order.new(&quot; 海尼根 &quot;, 51) warehouse = mock(Warehouse) mailer = mock(MailServer) order.set_mailer(mailer) mailer.have_receive(:send).ordered warehouse.have_receive(:has_inventory).\   with(any_args()).and_return(false).ordered order.fill(warehouse) # 沒有狀態的測試 end
Classical Testing v.s. Mockist Testing
Classical Test 盡量使用真實的物件
Classical Testing 如果太複雜,那就先造假
Mockist Testing 一切都是假的 包含物件與函式
Classical Test 結果對、就對
Mockist Testing 不只是結果,流程也要測試
Classical Testing Middle-out 你先決定你要完成的範圍, 然後實作這個範圍的所有物件 。
Mockist Testing Outside-in 你只針對一個類別 or element 其他都用假的
Classical Testing 利用 fixture fixtures 可以 reuse
Mockist Testing 不需要 fixture Mock object 不易 reuse
Classical Testing 一個 bug 會造成數個 element 的測試錯誤
Mockist Testing 只有產生 bug 的 element 會測試錯誤
結論 我下次會考慮寫測試的!

Mock Aren't Stub 讀後心得