Stub, Mock是甚麼?

Test Double, Dummy, Fake, Stubs, Spies, Mocks,第一次接觸這些英文名詞的時候,通常也就是剛接觸到測試相關技術的時候,一些文章,或者是課程、說明,或多或少都會帶到這幾個測試領域常見的名詞,之所以會為此專門寫一篇文章,其實除了在鞏固自己記憶之外,也順便備忘一下

結論

先說結論,概括性的稱呼 Test Double 就是測試替身,想像成替身演員的概念就是了。

  1. stub: 可以模擬回傳值、或是模擬物件狀態。為了取代、替換掉原有的程式
  2. mock: 可以用來驗證物件與其他物件的互動(包含次數、參數)
  3. fake: 實作一個輕量化的物件可用來取代原有的 SUT 依賴物件,該物件僅專心滿足於物件本身的功能,並不關心與其他物件的互動
  4. dummy: 跑龍套湊數的,哈哈哈

Gerard Meszaros 的定義

根據Martin FowlerMocks Aren’t Stubs一文,節錄文章中提到的幾個名詞,出自XUnit Test Patterns: Refactoring Test Code的作者Gerard Meszaros,有鑑於我的英文程度實在不好,節錄原文讓大家自己感受一下….

Meszaros uses the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes. The name comes from the notion of a Stunt Double in movies. (One of his aims was to avoid using any name that was already widely used.) Meszaros then defined five particular kinds of double:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test.
  • Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.
  • Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

於是我們直接到這本書的網站去看看它怎麼解釋的,基本上這網站的圖就已經超級清楚的了,所以我也不打算畫蛇添足的解釋了


Dummy

SUT 的某一些測試方法可能需要一些參數,但是這些參數其實沒用,但為了符合簽章方法,所以我們弄了一個測試替身,這就叫做 Dummy Object

Fake

Replace a component that the system under test (SUT) depends on with a much lighter-weight implementation.

Stubs

We replace a real object with a test-specific object that feeds the desired indirect inputs into the system under test.

Spies

Use a Test Double to capture the indirect output calls made to another component by the system under test (SUT) for later verification by the test.

Mocks

Replace an object the system under test (SUT) depends on with a test-specific object that verifies it is being used correctly by the SUT.

江湖人稱 91 的解釋

非常的精闢,也是我第一次接觸到的解釋

  • Stub:通常使用在驗證目標回傳值,以及驗證目標物件狀態的改變。
  • Mock:驗證目標物件與外部相依介面的互動方式

30 天快速上手 TDD Day7 - Stub, Mock, Fake 簡介 by 91