LoginSignup
0
0

【Go言語】echoのAPIをテストする [contextを使う]

Last updated at Posted at 2023-12-24

テスト用にプログラムを用意する

APIを作成する

【Go言語】echoのAPIをテストする [サーバーを起動させてテスト]【Go言語】echoのAPIをテストする [ハンドラー単体のテスト]をもとに少し改変します。
`go
package main

import "github.com/labstack/echo/v4"

func InitServer() *echo.Echo {
e := echo.New()

e.GET("/", func(c echo.Context) error {
	return c.String(200, "Hello, World!")
})

return e

}

func main() {
e := InitServer()
e.Logger.Fatal(e.Start(":8080"))
}
`

今回のテストではAPIで呼び出される関数を直接実行することでテストを行います。そのため、APIのハンドラとなる部分を外に出して置きます。

Helloという関数で切り出しました。

package main

import "github.com/labstack/echo/v4"

func InitServer() *echo.Echo {
	e := echo.New()

	e.GET("/", Hello)

	return e
}

func main() {
	e := InitServer()
	e.Logger.Fatal(e.Start(":8080"))
}

func Hello(c echo.Context) error {
	return c.String(200, "Hello World")
}

テストの作成

テスト側のコードは以下の通りです。とてもシンプルにできます

package main

import (
	"net/http"
	"net/http/httptest"
)

func TestAPI(t *testing.T)
{
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	w := httptest.NewRecorder()
	c := echo.New().NewContext(r, w)

	if err := Hello(c); err != nil {
		t.Fatal(err)
	}
}

contextの作成

echoで利用するコンテキストの作成はechoのライブラリ内にあるNewContext関数を利用します。
これに対してリクエストとレコーダーを渡すことでコンテキストを作成できます。

r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
c := echo.New().NewContext(r, w)

contextを引数に渡して関数を実行する

コンテキストを作成してそのまま引数に渡して上げれば関数が実行され、結果が帰ってきます。

値検証の部分は他の記事で何度も掲載したので今回は割愛していますが、レコーダーを利用してレスポンスの内容を検証することもできます

if err := Hello(c); err != nil {
  t.Fatal(err)
}

まとめ

このように直接関数を実行することでAPIのテストを行うことができます。全体のハンドラを実行する形式とにていますが、今回のように関数を切り出しておけば関数単位でテストを行うこともできます。

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