天天看點

Stubs和Mocks差別 (Stubs vs. Mocks)

翻譯自《Programming Groovy - Dynamic Productivity for the jdk Developer》的P243。

原文如下:

Stubs vs. Mocks

In the article “Mocks Aren’t Stubs,” (http://martinfowler.com/articles/mocksArentStubs.html ), Martin Fowler discusses the difference between stubs and mocks. A stub stands in for a real object. It simply reciprocates the coached expected response when called by the code being tested. The response is set up to satisfy the needs for the test to pass. A mock object does a lot more than a stub. It helps you ensure your code is interacting with its dependencies, the collaborators, as expected. It can keep track of the sequence and number of calls your code makes on the collaborator it stands in for. It ensures proper parameters are passed in to method calls. While stubs verify state, mocks verify behavior. When you use a mock in your test, it verifies not only the state but also the behavior of the interaction of your code with its dependencies. Groovy provides support for creating both stubs and mocks, as you will see in Section 16.10, Mocking Using the Groovy Mock Library, on page 254.

翻譯如下:

Stubs和Mocks的差別

在文章“Mocks不是Stubs”中(http://martinfowler.com/articles/mocksArentStubs.html ),馬丁·福勒讨論了stubs和mocks之間的差別。

stub代表的是一個真實的對象。在測試代碼中被調用時,它簡單的按照之前對它設定來應答調用者(對stub應答的設定過程稱這為訓練coach)。對stub應答的設定是為了通過測試。

mock對象要比stub做的事情多得多:

  • 幫你确定你的代碼和它的依賴(稱為合作者collaborator)有你期望的互動。
  • 跟蹤你的在Mock對象代表的合作者執行調用的序列和次數。
  • 保證方法調用傳遞了合适的參數。

stubs隻檢查的是狀态(state),而mocks檢查了行為(behavior)。在測試中使用mock,不僅檢查你測試和其依賴之間和狀态,而且還有行為。

PS:

順便推薦一下《Programming Groovy - Dynamic Productivity for the jdk Developer》這本書。

這是一本Groovy進階的書,入門可以先看一下《Groovy Recipes -Greasing the Wheels of jdk 》或是《Groovy Programming -An Introduction for jdk Developers》。Groovy的資料可以看看:http://blog.csdn.net/oldrat/archive/2010/02/22/5317366.aspx

《Programming Groovy》中有關的元程式設計的講解應該是最全面的。

更好的是,對動态語言的程式設計的最佳實踐也講了很多。