はじめに
こんにちは、H×Hのセンリツ大好きエンジニアです。(同担OKです😉)
Goでテストする時、ライブラリの関数どうテストするか迷いますよね🥹
そんな時は関数をモックして特定の動作を行うようにしちゃいましょう!
gomonkey
というライブラリを使用していきます。
gomonkeyとは
gomonkey is a library to make monkey patching in unit tests easy, and the core idea of monkey patching comes from Bouke, you can read this blogpost for an explanation on how it works.
gomonkeyは、単体テストでのモンキーパッチングを簡単に行うためのライブラリです。
モンキーパッチとは、既存のコードを実行範囲内で拡張または修正するというテクニックであり、これにより関数をモック化できるわけですね!
gomonkeyを使うことで依存関係を制御しやすくし、より効率良く単体テストを書くことができるようになるとのことです!
使用例
テスト元のコード
package random
import (
"math/rand"
)
func Rand() int {
randomNum := rand.Intn(10)
return randomNum
}
簡単な乱数生成の関数です。
0~9までのランダムな整数を生成し、返します。
しかし、テストを行う場合はランダム性を排除したいですよね🤔
毎回違う結果になると確かめようがないので。。。
テストコード
package random
import (
"math/rand"
"testing"
"github.com/agiledragon/gomonkey"
"github.com/stretchr/testify/assert"
)
func TestRand(t *testing.T) {
// rand.Intnをモックして常に0を返すように設定
patches := gomonkey.ApplyFunc(rand.Intn, func(n int) int {
return 0
})
// テスト終了時に、パッチをリセット
defer patches.Reset()
// モックされたrand.Intnを用いたRand()は常に0を返す
result := Rand()
// 期待される値と結果を比較
assert.Equal(t, 0, result)
}
上記のようにすれば、rand.Intn
の挙動を変更できるので不確実性を排除したテストコードを作成できます!
具体的には、
patches := gomonkey.ApplyFunc(rand.Intn, func(n int) int {
return 0
})
gomonkey.ApplyFunc
でrand.Intn
の返り値を強制的に0にしています。
このように記述することでライブラリの関数をモック化できます!
他にも、メソッドの挙動を変更するApplyMethodFunc
などさまざまな機能を用意しているので、是非見てみてください!
おわりに
単体テストでライブラリの挙動を制御したいときや、不確定要素を無くしたいときにgomonkey
を利用することができるかなと思います!🤗
最後までご覧いただきありがとうございました!
以上、センリツでした。🤓