LoginSignup
13
10

More than 5 years have passed since last update.

Go言語のtestで、json apiのレスポンス検証を行う

Posted at

golangでAPI開発してるとunitテストはもちろん書くけど

Rails Rspecみたいにrequestテスト(APIのレスポンス検証)もしたくなるよなー

goでやってみよう

package main  

import (      
  "bytes"     

  "io/ioutil" 
  "net/http"  
  "testing"   
)             

func TestRequest(t *testing.T) { 
var j = []byte(`
{
  "id": "test"
}`)

url := "http://IPADDRESS/ENDPOINT"

//postrequest作成
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

//headerをセット
req.Header.Set("Content-Type", "application/json")                

//httpクライアント
client := &http.Client{} 

//実行
resp, err := client.Do(req) 
if err != nil {             
  panic(err)                
}     

//body使わなくなったら閉じる                      
defer resp.Body.Close()     

//エラー検証
if err != nil {             
  t.Error(err)              
  return                    
}                           

//ステータスコード確認                 
if resp.StatusCode != 200 { 
  t.Error(resp.StatusCode)  
  return                    
}                           

//レスポンスBODY取得
body, _ := ioutil.ReadAll(resp.Body)

actual := string(body)
expected := `{"id":"test-id-desuyo"}`

if actual != expected {     
  t.Error("response error") 
}                           
return
}

こんな感じでhttp.Clinetを使えば実装できますよ!

本当はnet/http/httptestというやつもいてるけど、今回は使わずにやりました。

13
10
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
13
10