Mock Database(模擬資料庫)輔助單元測試的優點
- 將測試資料與正式資料庫隔離,避免資料衝突。
- 不需連接正式資料庫,節省測試時間。
- 容易模擬極端狀況,以達測試覆蓋率 100%。
gomock 框架
從 GitHub gomock 找到 mockgen tool 的安裝指令。
安裝後依序執行以下指令:
// 檢視 mockgen tool 是否存在
$ ls -l ~/go/bin
// 檢視 mockgen 是否可在任何位置使用
$ which mockgen // 檢視結果為 mockgen not found,因為尚未設定 PATH 環境變數。
// 在 Vim 編輯器設定 PATH 環境變數(以下二擇一)
$ vi ~/.zshrc // 透過 zsh 開啟 Vim 編輯器
$ vi ~/.bash_profile // 透過 bash 開啟 Vim 編輯器
// 在 Vim 編輯器執行以下設定
export PATH=$PATH:~/go/bin(輸入完畢用 :wp 儲存離開)
// 離開 Vim 編輯器後,用以下指令重新讀取 zshrc file
$ source ~/.zshrc
完成以上操作後,再次輸入指令 $ which mockgen,
若看到 /Users/username/go/bin/mockgen 之類的訊息表示完成設定。
接著可用指令 $ mockgen -help 檢視 mockgen 的使用說明
mockgen has two modes of operation: source and reflect.
Source mode generates mock interfaces from a source file.
It is enabled by using the -source flag. Other flags that
may be useful in this mode are -imports and -aux_files.
Example:
mockgen -source=foo.go [other options]
Reflect mode generates mock interfaces by building a program
that uses reflection to understand interfaces. It is enabled
by passing two non-flag arguments: an import path, and a
comma-separated list of symbols.
Example:
mockgen database/sql/driver Conn,Driver
-aux_files string
(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.
-build_flags string
(reflect mode) Additional flags for go build.
-copyright_file string
Copyright file used to add copyright header
-debug_parser
Print out parser results only.
-destination string
Output file; defaults to stdout.
-exec_only string
(reflect mode) If set, execute this reflection program.
-imports string
(source mode) Comma-separated name=path pairs of explicit imports to use.
-mock_names string
Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.
-package string
Package of the generated code; defaults to the package of the input with a 'mock_' prefix.
-prog_only
(reflect mode) Only generate the reflection program; write it to stdout and exit.
-self_package string
The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.
-source string
(source mode) Input Go source file; enables source mode.
-version
Print version.
-write_package_comment
Writes package documentation comment (godoc) if true. (default true)