almost 8 years ago

Stub

一般來說,驗證「回傳值」或驗證「狀態改變時」,經常會使用 Stub 手法。
因為在這兩種狀況中,即便這個 method 有可能去呼叫「外部物件」,坦白來說,我們「不在乎」。


比如說這段程式碼

class Post
  def visit!
    update_visit_cache_to_memory!
    self.increment_counter(:visit_count, 1)
  end

  def current_visit_count
    update_visit_cache_to_memory!
    return visit_count
  end
end

因為我們只在乎「當下這個物件」。所以寫測試時,我們會 stub 掉 update_visit_cache_to_memory!「呼叫 外部 method」這件事。以取得我們要的結果。

Mock

「模擬」與一個「協作者」的互動,設立一個「會收到指定訊息」的期望,去驗證互動是否真的有發生。

← [RSpec] 進階測試系列概念 - Part 1 單元測試的種類 [RSpec] 進階測試系列概念 - Part 3 使用 stub →
 
comments powered by Disqus