單元測試不是有寫就好
unit test 要能夠不影響彼此的獨立運作
不能受限與某個時間點或某個服務
單元測試的目的
-
保護
功能而不是程式- 保護程式會被程式設計綁架
-
幫助重構
單元測試應該要像我們的其他程式碼一樣好好地維護

具體地表明此測試在測什麼
「好的」單元測試
-
暴露意圖
- 建立 user 後檢查餘額
-
version 1
UserObj user = new UserObj(); user.setName(“Kuma”); long userId = userMapper.insert(user); AccountObj account = new Account(); account.setBalance(1,000); account.setUser(user.getId()); accountMapper.insert(account); account.getBalance(userId); assertEquals(1,000, userId) -
version 2
create_user(1,000); when_get_balance(); then_result_is(1,000);
-
「適當且簡單」的檢查
-
驗回傳 > 驗狀態 > 驗互動
-
驗回傳
-
最接近 User 的的實際狀況
-
測試是自己程式的第一個 User
-
-
驗狀態
-
驗互動
-
Mockito.verify(kafkaClient.put(“t”, “hello world”), times(2));
-
mocking
-
被程式實作綁架
-
當不得不驗互動的場景越來越多,請回頭看看介面設計有什麼問題。
-
-
-
珍惜生命,遠離框架
-
測功能,不要測類別 → 獨立於架構
-
分開測

- 組再一起不一定是正常的
-
把程式當成黑盒子測試

- 更放心地重構,不用擔心架構的重構會影響功能
-
實踐:邊寫邊重構
-
程式功能
-
程式架構
-
測試
三點不動一點不動:TDD