A Go Test Helper I Swear By

This article was automatically translated from Japanese by AI. Read the original Japanese version →

Not just in Go, when writing tests you often end up writing the exact same patterns over and over. So I'd like to introduce a helper function that I rely on heavily.

When writing functions in Go, it's very common to return both a value and an error. So I prepare the following helper function:

// CheckErr エラーの存在チェック
func CheckErr(t *testing.T, i int, ok bool, err error) bool {
    t.Helper()
    if ok {
        if err != nil {
            t.Errorf("[%d] err should be nil, but got:%s", i, err)
            return true
        }
        return false
    }
    if err == nil {
        t.Errorf("[%d] err should not be nil, but got:%s", i, err)
        return true
    }
    return true
}

It returns false when you should proceed to check the non-err return value.
i takes the loop index from table-driven tests (TDD)—when doing TDD, it's easy to lose track of which case threw the error.
ok is a boolean indicating whether the test case expects no error (true means no error expected).
err takes the error returned by the function under test.

Here's an example of how to use it.
When a function returns an error, the other return values will just be zero values anyway, so there's no need to check them.

func Something(x int) (string, error){
    if x < 0 {
        return "", errors.New("")
    } else {
        return strconv.Itoa(x), nil
    }
}

func TestSomething(t *testing.T){
    testTable := []struct{
        x int
        res string
        isErr bool
    }{
        {x: 1, res: "1", isErr: false},
        {x: -1, isErr: true},
    }
    for i, tt := range testTable {
        res, err := Something(i)
        if !CheckErr(t, i, tt.isErr, err) {
            if w, g := tt.x, res; w != g {
                t.Errof("unmatch w: %s, g: %s", w, g)
            }
        }
    }
}

Furthermore, you might also have cases where an error is extended (?) to return an error code.

// ErrCodeを返すMyErrorがあるとする
type MyError interface{
    Error() string
    ErrCode() uint32
}

type HogeError struct{}

func (e HogeError) Error() string {
    return "error"
}

func (e HogeError) ErrCode() uint32 {
    return 1001
}

In that case, you can extend CheckErr like this:

// CheckErrCode 想定されるエラーコードがあればそれを確認する
func CheckErrCode(t *testing.T, i int, code uint32, err error) bool {
    t.Helper()
    noErr := code == 0
    if !noErr && err != nil {
        if terr, ok := errors.Cause(err).(MyError); ok {
            if w, g := terr.ErrCode(), code; w != g {
                t.Errorf("[%d] err_code unmached. want:%d, but got %d", i, w, g)
            }
        } else {
            t.Errorf("[%d] err type unmached. %T", i, terr)
        }
    }
    return CheckErr(t, i, noErr, err)
}

Since it's just a simple function without passing callbacks or defining extra structs, it's super easy to extend as needed and very handy.