筆者心裡OS: 其他鐵人太利害了,都能準時完成、發文。我每篇文章至少要兩三個小時才能產出來,所以目前欠的技術債有點多……囧
聊完了單元測試的概念與原則,各位看倌一定覺得筆者都在說廢話。說了那麼多,還是不知道要怎麼做單元測試。
在我們開始聊 Test Double 之前,筆者先分享一個網站 xUnit Patterns.com 給各位看倌,這個網站是 xUnit Test Patterns: Refactoring Test Code 的作者 Gerard Meszaros 建立的網站。
雖然筆者還沒有拜讀過 xUnit Test Patterns 這本高達 833 頁的的實體書,不確在網站內容與實體書的內容差異有多少。但就網站內公開的資訊,就令筆者收獲良多。
但是……
它的內容很多都有套上 Pattern,算是有點硬的資料,如果沒有 Pattern 的基礎,可能會吃力了點。不過,如果要進一步了解單元測試,很推薦各位看倌花點時間研讀。
We replace a component on which the SUT depends with a "test-specific equivalent."
上圖是 Gerard Meszaros 用來說明 Test Double 概念的圖,搭配文字說明,大致就可以明白 Test Double 的作用與意義。
The "system under test". It is short for "whatever thing we are testing" and is always defined from the perspective of the test. When we are writing unit tests the system under test (SUT) is whatever class (a.k.a. CUT), object (a.k.a. OUT) or method(s) (a.k.a. MUT) we are testing; when we are writing customer tests, the SUT is probably the entire application (a.k.a. AUT) or at least a major subsystem of it.
The parts of the application that we are not verifying in this particular test may still be involved as a depended-on component (DOC).
簡單來說,就是待測試的項目,不管我們要測的是類別、物件還是方法,都可以統稱 SUT。
An individual class or a large-grained component on which the system under test (SUT) depends.
The dependency is usually one of delegation via method calls.
In test automation, it is primarily of interest in that we need to be able to examine and control its interactions with the SUT to get complete test coverage.
在 Gerard Meszaros 的《xUnit Test Pattern》中,針對 Test Double ,將其分為五種類型,Dummy Object, Test Stub, Test Spy, Mock Object, Fake Object。但我們只針對比較常使用的 Stub, Mock, Fake 進行討論。
引用某個函數的目標,不外乎是為了取得回傳資料、變更內部狀態、引發物件與物件之間的互動。所以進行單元測試,為了驗證函數內的邏輯是否正確,自然而然的,分為三種不同的測試方式,以應對不同的情境。
Checks the value returned from a function.
Checks the noticeable behavior changes in the system under test, after changing its state.
Tests how an object sends input to or receives input from other objects—how that object interacts with other objects.