@@ -2,6 +2,7 @@ package server
22
33import (
44 "encoding/json"
5+ "fmt"
56 "io/ioutil"
67 "net/http"
78 "net/http/httptest"
@@ -47,3 +48,65 @@ func TestFetchGophers(t *testing.T) {
4748 t .Errorf ("expected %d gophers, got: %d gopher" , sample .Gophers , got )
4849 }
4950}
51+
52+ func TestFetchGopher (t * testing.T ) {
53+
54+ testData := []struct {
55+ name string
56+ g * gopher.Gopher
57+ status int
58+ err string
59+ }{
60+ {name : "gopher found" , g : gopherSample (), status : http .StatusOK },
61+ {name : "gopher not found" , g : & gopher.Gopher {ID : "123" }, status : http .StatusNotFound , err : "Gopher Not found" },
62+ }
63+
64+ for _ , tt := range testData {
65+ t .Run (tt .name , func (t * testing.T ) {
66+ uri := fmt .Sprintf ("/gophers/%s" , tt .g .ID )
67+ req , err := http .NewRequest ("GET" , uri , nil )
68+ if err != nil {
69+ t .Fatalf ("could not created request: %v" , err )
70+ }
71+
72+ repo := inmem .NewGopherRepository (sample .Gophers )
73+ s := New (repo )
74+
75+ rec := httptest .NewRecorder ()
76+ s .Router ().ServeHTTP (rec , req )
77+
78+ res := rec .Result ()
79+
80+ defer res .Body .Close ()
81+ if tt .status != res .StatusCode {
82+ t .Errorf ("expected %d, got: %d" , tt .status , res .StatusCode )
83+ }
84+ b , err := ioutil .ReadAll (res .Body )
85+ if err != nil {
86+ t .Fatalf ("could not read response: %v" , err )
87+ }
88+
89+ if tt .err == "" {
90+ var got * gopher.Gopher
91+ err = json .Unmarshal (b , & got )
92+ if err != nil {
93+ t .Fatalf ("could not unmarshall response %v" , err )
94+ }
95+
96+ if * got != * tt .g {
97+ t .Fatalf ("expected %v, got: %v" , tt .g , got )
98+ }
99+ }
100+ })
101+ }
102+
103+ }
104+
105+ func gopherSample () * gopher.Gopher {
106+ return & gopher.Gopher {
107+ ID : "01D3XZ3ZHCP3KG9VT4FGAD8KDR" ,
108+ Name : "Jenny" ,
109+ Age : 18 ,
110+ Image : "https://storage.googleapis.com/gopherizeme.appspot.com/gophers/0ceb2c10fc0c30575c18ff1defa1ffd41501bc62.png" ,
111+ }
112+ }
0 commit comments