16/01/2020 - GO
There are a few ways to test endpoints within Golang but I am showing you the most common ones here.
package main
import (
"log"
"net/http"
)
func main() {
handler := http.NewServeMux()
handler.HandleFunc("/api/v1/users", users)
log.Fatal(http.ListenAndServe(":8080", handler))
}
func users(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("inanzzz"))
}
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func Test_users(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/api/v1/users", nil)
if err != nil {
t.Fatal(err)
}
res := httptest.NewRecorder()
handler := http.HandlerFunc(users)
handler.ServeHTTP(res, req)
if http.StatusOK != res.Code {
t.Error("expected", http.StatusOK, "got", res.Code)
}
if "inanzzz" != res.Body.String() {
t.Error("expected inanzzz got", res.Body.String())
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func Test_users(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
res := httptest.NewRecorder()
users(res, req)
// Instead of lines below, you can just use res.Code and res.Body.String() directly.
result := res.Result()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
t.Fatal(err)
}
result.Body.Close()
if http.StatusOK != result.StatusCode {
t.Error("expected", http.StatusOK, "got", result.StatusCode)
}
if "inanzzz" != string(body) {
t.Error("expected inanzzz got", string(body))
}
}