Skip to content

Instantly share code, notes, and snippets.

@duaneking
Created October 26, 2022 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duaneking/4526fe0d11dcf7a6c14374bc365439b4 to your computer and use it in GitHub Desktop.
Save duaneking/4526fe0d11dcf7a6c14374bc365439b4 to your computer and use it in GitHub Desktop.
The best way I have found to test Gin Endpoints in GO-Lang, end to end, I'n a simple and easy to maintain way. I'm doing this pattern + dependency injection + the repository design pattern with data driven and seeded tests on every build.
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestGetHttpRegisterFlowPagesLoadFull(t *testing.T) {
var tests = []struct {
url string
mustContain string
}{
{"/v0/register", "🎃"},
{"/v0/verify", "The token from your email."},
{"/v0/login", "🌎"},
}
engine := GetGin(false)
for _, tt := range tests {
testname := fmt.Sprintf("%s=>%s", tt.url, tt.mustContain)
t.Run(
testname,
func(t *testing.T) {
DoGetWebTest(t, engine, tt.url, tt.mustContain)
},
)
}
}
func DoGetWebTest(t *testing.T, engine *gin.Engine, url string, mustContain string) {
req, _ := http.NewRequest("GET", url, nil)
testHTTPResponse(t, engine, req, func(w *httptest.ResponseRecorder) bool {
statusOK := w.Code == http.StatusOK
p, err := io.ReadAll(w.Body)
pageOK := err == nil && strings.Index(string(p), mustContain) > 0
return statusOK && pageOK
})
}
func testHTTPResponse(t *testing.T, r *gin.Engine, req *http.Request, f func(w *httptest.ResponseRecorder) bool) {
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if !f(w) {
t.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment