This example shows us how we can mock a non-existent endpoint/router and a non-existent HTTP server in Golang. Technically you are writing your tests before writing the code.


Test


package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
)

func Test_users(t *testing.T) {
srv := serverMock()
defer srv.Close()

req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/users", srv.URL), nil)
if err != nil {
t.Error(err)
}

res, err := http.DefaultClient.Do(req)
if err != nil {
t.Error(err)
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}

if http.StatusOK != res.StatusCode {
t.Error("expected", http.StatusOK, "got", res.StatusCode)
}
if "Hello" != string(body) {
t.Error("expected Hello got", string(body))
}
}

func serverMock() *httptest.Server {
handler := http.NewServeMux()
handler.HandleFunc("/api/v1/users", usersMock)

srv := httptest.NewServer(handler)

return srv
}

func usersMock(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
}