15
11

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.

apiサーバーのテスト書くときによく使う型の作り方

Last updated at Posted at 2015-10-04

テストを書く時によく使う型の生成方法。
たぶんいくつもあるだろうけれど、普段よく使っているもの。

io.Reader

var reader io.Reader = strings.NewReader("")

io.ReadCloser

r := strings.NewReader("")
var readCloser io.ReadCloser = ioutil.NopCloser(r)

http.ResponseWriter

var w http.ResponseWriter = httptest.NewRecorder()

http.Request

req, err := http.ReadRequest(bufio.NewReader(strings.NewReader("GET / HTTP/1.0\n\n")))

ユースケース

http.Handler

よくhttpサーバー作るときに見るあれ。

main.go
package main

import "net/http"

func handler(w http.ResponseWriter, r *http.Request) {
  w.WriteHeader(http.StatusOK)
}

func main() {
  http.HandleFunc("/", handler)
  http.ListenAndServe(":8080", nil)
}
main_test.test
package main

import (
  "io/ioutil"
  "net/http"
  "net/http/httptest"
  "net/url"
  "strings"
  "testing"
)

func TestHandler(t *testing.T) {
  r := &http.Request{}
  // 必要にあわせて
  // var err error
  // if r.URL, err = url.Parse("http://localhost"); err != nil {
  //   t.Fatal(err)
  // }
  // r.Body = ioutil.NopCloser(strings.NewReader(""))
  w := httptest.NewRecorder()
  handler(w, r)

  if w.Code != http.StatusOK {
    t.Error("200じゃない")
  }
}

その変数や型がinterfaceに対応しているかを確認する

api全然関係ないけれど、よく使うのでこれも。

変数

s := strings.NewReader("")
var _ io.Reader = s
var _ io.Reader = "abc" // cannot use "abc" (type string) as type io.Reader in assignment

package main

type E struct{}

func (_ E) Error() string {
	return ""
}

type F struct{}

func main() {
	var _ error = (*E)(nil)
	var _ error = (*F)(nil) // cannot use (*F)(nil) (type *F) as type error in assignment
}
15
11
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
15
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?