1
0

More than 1 year has passed since last update.

GoのテストでJSONのレスポンスから値を取得して比較したい

Posted at

はじめに

Goのテストを書くときに、レスポンスのBodyの内容を比較する際に以下のようなコードを書いていました

assert.Equal(t, w.Body.String(), "{\"msg\":\"pong\"}")

しかし、この中の要素を取得してテストを書く機会が訪れたのでまとめます

問題

bcryptを利用して、レスポンスのBodyにはいっている暗号化されたパスワードを取得して、それを複合して比較して同じことを確かめるテストを書こうとしました

そこでレスポンスから暗号化したパスワードのみを取得する必要がありました

解決方法

以下のようにすることでレスポンスからパスワードのみを取得することができました

controller_test.go
		req, _ := http.NewRequest("POST", "/sign_up", body)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)

		jsonBytes := []byte(w.Body.String())
		data := new(Response)
		if err := json.Unmarshal(jsonBytes, data); err != nil {
				fmt.Println("JSON Unmarshal error:", err)
				return
		}
		
		assert.Equal(t, data.Password, "暗号化した文字列")

おわりに

構造体がやはりまだ慣れておらず解決まで少し時間がかかってしまいました
この方法は今後も重宝しそうです

参考

1
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
1
0