LoginSignup
1
1

Goのテストコードを書く時パッケージ名に_testをつけるべきか?

Posted at

Goでテストを書きたい時にテストコードには_testのsuffixをつける時と

同一パッケージでテストコードを書いている例があります。

どちらが正しい書き方なのか調べてみました。

_testをつけている例

stringsパッケージでは_testのsuffixをつけてテストコードを書いています。
https://go.dev/src/strings/search_test.go

// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package strings_test

_testをつけていない例

bzip2パッケージでは_testをつけずにテストコードを書いています。


// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bzip2

_testをつけるのとつけないので何が違うのか?

_testがついていると別のパッケージとして認識されてしまいprivateな関数の
テストを行うことができません。

例:

sample.go
package sample
func add(a int, b int)int {
    return a+b
}
sample_test.go
package sample_test

import "testing"

func Test_add(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		want int
	}{
		// TODO: Add test cases.
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
            // addはpackage内変数なのでsample_test.goから呼び出すことができない
			if got := add(tt.args.a, tt.args.b); got != tt.want {
				t.Errorf("add() = %v, want %v", got, tt.want)
			}
		})
	}
}

使い分けはどうすべきなのか

goでテストコードを書くときは_testをつけるべきなのでしょうか?

それともつけずに同一パッケージ内で行うべきなのでしょうか?

Stack Overflowに似た質問がありました。

The fundamental difference between the three strategies you've listed is whether or not the test code is in the same package as the code under test. The decision to use package myfunc or package myfunc_test ?in the test file depends on whether you want to perform white-box or ?black-box testing.
There's nothing wrong with using both methods in a project. For instance, you could have myfunc_whitebox_test.go and myfunx_blackbox_test.go.

すなわち
テストファイルでのパッケージの選択は、ホワイトボックステストかブラックボックステストを行いたいかどうかによって異なり、
プロジェクトで両方の方法を使用することは問題ないとのことでした。

用語説明

ホワイトボックステスト

ホワイトボックステストは、すべてのプログラムが意図したとおりに動作しているかを確認するためのテストです。プログラムの構造やエンジニアが作成したロジック、制御の流れなどが正常かどうかを検証するため、「作り手側のテスト」といわれています。

出典:https://hnavi.co.jp/knowledge/blog/white-box-test/

ブラックボックステスト

ブラックボックステストは、システム自体の仕様を満たしているかどうかを確認する機能のテストです。画面表示などユーザーインタフェースの不具合やレイアウト崩れなど、正しい出力ができているかを確認するため、「ユーザー側のテスト」といわれています。

出典:https://hnavi.co.jp/knowledge/blog/white-box-test/

プロジェクト全体でテストコードは_testをつけるようにするつけないようにするという
ルール決めを行うのではなくホワイトボックステスト (private関数も含めてpackage内の関数全ての挙動を確認したい時)
かブラックボックステスト(packageを外部から呼び出すことを想定してexport
している関数に関しての挙動を確認したい時)どちらをテストしたいかによって
_testをつける、つけないは判断すべきだということでした。

1
1
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
1
1