Unit testing 上的一些省思

去除測試的壞味道 — 多一個 function assign value

前言

這幾個月重新檢視寫測試的一些經驗發現有很多地方可以做得更好,所以寫了這篇短文。

Separation of concerns

相信下面的程式邏輯很容易看的出來我要對一個 list 做 pop ,在 function 內作一些簡單的處理之後回傳這個值。

//....class AClass {

function GetValue(){
//code goes here
let value = this.list.pop(); //this line hard to test
//code goes here
return value;
}

//} end of a class

但做測試是另外一個故事了,我要怎麼 mock 那個 value 確保我的演算法是對的?

一開始對單元測試能理解但是很難實踐,我也是,我一開始即便寫了很多單元測試也是苦於不知道怎麼對一個 function 進行測試,常常寫成整合測試,直到幾個月以前去 Joey Chen 那邊上了單元測試相關的課程,一陣子的實作之後,我有天突然理解所謂的加一層的概念,也就是實作程式邏輯變成下面的樣子。

//....class AClass {

function GetValue(){
//code goes here
let value = this.PopListData(); // we can stub this function in unit test file
//code goes here
return value;
}

function PopListData(){
return this.list.pop(); //seperation of concerns
}

//} end of a class

這樣就可以透過 framework 針對這 function 去 mock 出一個 return 的值了。

--

--