From b1380d5ca8be44753d83c4d730563bb4590b2b6c Mon Sep 17 00:00:00 2001 From: "javier.juarez" Date: Sat, 16 Jul 2022 14:49:28 +0200 Subject: [PATCH] test: Changes to add more coverage --- cmd/main.go | 11 +++++++++-- cmd/main_test.go | 28 ++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 7c25fb7..f051fe7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,7 +9,8 @@ import ( const envVariableKey = "DEFAULT_NAME" -func main() { +func setupRouter() *gin.Engine { + gin.ForceConsoleColor() router := gin.Default() router.GET("/sayhi", func(context *gin.Context) { @@ -22,5 +23,11 @@ func main() { greetingMessage := greeting.Greeting(name) context.JSON(http.StatusOK, gin.H{"message": greetingMessage}) }) - router.Run() // listen and server on 0.0.0.0:8080 + + return router +} + +func main() { + router := setupRouter() + router.Run() // listen and server on 0.0.0.0:${PORT} } diff --git a/cmd/main_test.go b/cmd/main_test.go index 1ee1d87..b4eb402 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -1,13 +1,37 @@ package main import ( + "fmt" + "net/http" + "net/http/httptest" "testing" + "github.com/jjuarez/dagger-golang-example/internal/greeting" "github.com/stretchr/testify/assert" ) -func TestMain(t *testing.T) { +func TestWithoutName(t *testing.T) { t.Run("your real tests should go here", func(t *testing.T) { - assert.True(t, true, "This's just a placeholder") + testRouter := setupRouter() + record := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "/sayhi", nil) + want := fmt.Sprintf("{\"message\":\"Hi, %s!\"}", greeting.DefaultName) + testRouter.ServeHTTP(record, req) + + assert.Equal(t, http.StatusOK, record.Code) + assert.Equal(t, want, record.Body.String()) + }) +} + +func TestWithName(t *testing.T) { + t.Run("your real tests should go here", func(t *testing.T) { + testRouter := setupRouter() + record := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "/sayhi/testing", nil) + want := "{\"message\":\"Hi, testing!\"}" + testRouter.ServeHTTP(record, req) + + assert.Equal(t, http.StatusOK, record.Code) + assert.Equal(t, want, record.Body.String()) }) }