0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goでテスト

標準パッケージのtestingを用いたテストの書き方についてみていきます。

テスト対象は先日作成した多層キャッシュプログラムです。

テスト対象↓

adapters/redis_adapter.go
package adapters

import "github.com/go-redis/redis"


type  RedisAdapter struct {
	client *redis.Client
}

func NewRedisAdapter() *RedisAdapter {
	return &RedisAdapter{
		client: redis.NewClient(&redis.Options{
			Addr:     "localhost:6381",
			Password: "",
			DB:       0,
		}),
	}
}

func (adapter *RedisAdapter) Get(key string) string {
	val, err := adapter.client.Get(key).Result()
	if err != nil {
		return ""
	}
	return val
}

func (adapter * RedisAdapter) Set(key string, value string) {
	adapter.client.Set(key, value, 0)
}

func (adapter * RedisAdapter) Delete(key string) {
	adapter.client.Del(key)
}j

命名規則としてファイル名の末尾は_test.goである必要があります。

touch adapters/redis_adapter_test.go

関数名の命名規則はTestから始まる必要があります。

adapters/redis_adapter_test.go
package adapters

import (
	"testing"
)

func TestRedisAdapter_Get(t *testing.T) {
	adapter := NewRedisAdapter()

	adapter.Set("key", "value")
	want := "value"
	got := adapter.Get("key")

	if got != want {
		t.Error("失敗")
	}
}

testingassert関数は無いため、期待と実際が異なった際に、
t.Error("失敗")にしています。

テスト実行

 go test ./adapters

ok  	in_memory_cache_demo/adapters	0.286s
shuyafukushima@Shuya:~/programing/in_memory_cache_demo

-vオプションをつけることでより詳細な出力を得ることができます。

go test -v ./adapters
=== RUN   TestRedisAdapter_Get
--- PASS: TestRedisAdapter_Get (0.02s)
PASS
ok  	in_memory_cache_demo/adapters	0.124s
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?