2
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?

More than 5 years have passed since last update.

突っ込む時はinterfaceで貰う時はstruct

Posted at

困ったこと

こういうテストコードを書いていました。
テスト用にpng画像のデータをbase64でコード化しておいて使い回していました。

test_image.go
package test_image

import (
	"bytes"
	"encoding/base64"
)

func GetTestAsset(key string) io.Reader {
	src := "iVBORw0KGgoAAAAN..." // png画像のbase64データ
	data, _ := base64.StdEncoding.DecodeString(src)
	r := bytes.NewReader(data)

	return r
}

そしてテスト本体はこんな感じです。

func Test(t *testing.T) {
	t.Run("Hoge hoge test", func(t *testing.T) {
		asset := test.GetTestAsset()

		resultBuffer := HogeReadAsset(asset)

		buf, _ := ioutil.ReadAll(asset)

		assert.Equal(t, buf, b) // Fail
	})
}

テスト対象メソッドのHogeReadAsset()asset.Read()で最後までシークされる想定なので、
その後にioutil.ReadAll()をしても空配列しか返ってこないのでテストが失敗するのです。

io.ReaderのSeek位置を初期化できればいいのになあと思うのですが、
io.ReaderにはRead()しか実装されていません。

io/io.go
type Reader interface {
	Read(p []byte) (n int, err error)
}

さあ困ったどうしよう。

最初からstructを返せば良い

というわけでこうしました。

test_image.go
(省略)

func GetTestAsset(key string) *bytes.Reader {
	src, _ := "iVBORw0KGgoAAAAN..." // png画像のbase64データ
	data, _ := base64.StdEncoding.DecodeString(src)
	r := bytes.NewReader(data)

	return r
}

bytes.ReaderSeek()を持ってます。

func (r *Reader) Seek(offset int64, whence int) (int64, error) {

これでテストが通ります。

以上

2
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
2
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?