Created
October 26, 2022 02:06
-
-
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.
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" | |
"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