0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

【Go】ライブラリの関数をテストする時はgomonkeyでモックしちゃえ!

Posted at

はじめに

こんにちは、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を使うことで依存関係を制御しやすくし、より効率良く単体テストを書くことができるようになるとのことです!

使用例

テスト元のコード

random.go
package random

import (
    "math/rand"
)

func Rand() int {
    randomNum := rand.Intn(10)
    return randomNum
}

簡単な乱数生成の関数です。
0~9までのランダムな整数を生成し、返します。

しかし、テストを行う場合はランダム性を排除したいですよね🤔
毎回違う結果になると確かめようがないので。。。

テストコード

test_rand.go
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の挙動を変更できるので不確実性を排除したテストコードを作成できます!
具体的には、

test_rand.go
patches := gomonkey.ApplyFunc(rand.Intn, func(n int) int {
        return 0
    })

gomonkey.ApplyFuncrand.Intnの返り値を強制的に0にしています。
このように記述することでライブラリの関数をモック化できます!

他にも、メソッドの挙動を変更するApplyMethodFuncなどさまざまな機能を用意しているので、是非見てみてください!

おわりに

単体テストでライブラリの挙動を制御したいときや、不確定要素を無くしたいときにgomonkeyを利用することができるかなと思います!🤗

最後までご覧いただきありがとうございました!
以上、センリツでした。🤓

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0