Created
December 10, 2018 09:29
-
-
Save allyraza/77a72b8d2427249f8110d3a48a94925f to your computer and use it in GitHub Desktop.
go handler test example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
type Repo interface { | |
GetOne() string | |
} | |
type PostRepo struct{} | |
func (pr *PostRepo) GetOne() string { | |
return "some random stuff" | |
} | |
func homepageHandler(repo Repo) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, repo.GetOne()) | |
} | |
} | |
func postHandler() http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
if r.Method != http.MethodPost { | |
return | |
} | |
r.ParseForm() | |
fmt.Fprintf(w, r.FormValue("username")) | |
} | |
} | |
func main() { | |
repo := &PostRepo{} | |
http.HandleFunc("/", homepageHandler(repo)) | |
http.HandleFunc("/post", postHandler()) | |
http.ListenAndServe(":8080", nil) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"net/http/httptest" | |
"net/url" | |
"strings" | |
"testing" | |
) | |
type testPostRepo struct{} | |
func (tpr *testPostRepo) GetOne() string { | |
return "test" | |
} | |
type RequestFunc func(url string, params url.Values) *httptest.ResponseRecorder | |
func request(t *testing.T, method string, handler http.HandlerFunc) RequestFunc { | |
return func(url string, params url.Values) *httptest.ResponseRecorder { | |
r, err := http.NewRequest(method, url, strings.NewReader(params.Encode())) | |
if err != nil { | |
t.Error(err) | |
} | |
// only encode body when post method is used | |
if method == http.MethodPost { | |
r.Header.Set("Content-Type", | |
"application/x-www-form-urlencoded; param=value", | |
) | |
} | |
w := httptest.NewRecorder() | |
handler(w, r) | |
return w | |
} | |
} | |
func TestHomepageHandler(t *testing.T) { | |
repo := &testPostRepo{} | |
Get := request(t, http.MethodGet, homepageHandler(repo)) | |
w := Get("/", url.Values{}) | |
got := w.Body.String() | |
want := "test" | |
if got != want { | |
t.Fatalf("Want: %v, Got: %v\n", want, got) | |
} | |
} | |
func TestPostHandler(t *testing.T) { | |
Post := request(t, http.MethodPost, postHandler()) | |
params := url.Values{"username": []string{"John"}} | |
w := Post("/post", params) | |
got := w.Body.String() | |
want := params.Get("username") | |
if got != want { | |
t.Fatalf("Want: %v, Got: %v\n", want, got) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment