Skip to content

Commit 82aa7cf

Browse files
authored
Merge pull request #9 from jjuarez/feature/gin-tests
test: Changes to add more coverage
2 parents 0164449 + b1380d5 commit 82aa7cf

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

cmd/main.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import (
99

1010
const envVariableKey = "DEFAULT_NAME"
1111

12-
func main() {
12+
func setupRouter() *gin.Engine {
13+
gin.ForceConsoleColor()
1314
router := gin.Default()
1415

1516
router.GET("/sayhi", func(context *gin.Context) {
@@ -22,5 +23,11 @@ func main() {
2223
greetingMessage := greeting.Greeting(name)
2324
context.JSON(http.StatusOK, gin.H{"message": greetingMessage})
2425
})
25-
router.Run() // listen and server on 0.0.0.0:8080
26+
27+
return router
28+
}
29+
30+
func main() {
31+
router := setupRouter()
32+
router.Run() // listen and server on 0.0.0.0:${PORT}
2633
}

cmd/main_test.go

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,37 @@
11
package main
22

33
import (
4+
"fmt"
5+
"net/http"
6+
"net/http/httptest"
47
"testing"
58

9+
"github.com/jjuarez/dagger-golang-example/internal/greeting"
610
"github.com/stretchr/testify/assert"
711
)
812

9-
func TestMain(t *testing.T) {
13+
func TestWithoutName(t *testing.T) {
1014
t.Run("your real tests should go here", func(t *testing.T) {
11-
assert.True(t, true, "This's just a placeholder")
15+
testRouter := setupRouter()
16+
record := httptest.NewRecorder()
17+
req, _ := http.NewRequest("GET", "/sayhi", nil)
18+
want := fmt.Sprintf("{\"message\":\"Hi, %s!\"}", greeting.DefaultName)
19+
testRouter.ServeHTTP(record, req)
20+
21+
assert.Equal(t, http.StatusOK, record.Code)
22+
assert.Equal(t, want, record.Body.String())
23+
})
24+
}
25+
26+
func TestWithName(t *testing.T) {
27+
t.Run("your real tests should go here", func(t *testing.T) {
28+
testRouter := setupRouter()
29+
record := httptest.NewRecorder()
30+
req, _ := http.NewRequest("GET", "/sayhi/testing", nil)
31+
want := "{\"message\":\"Hi, testing!\"}"
32+
testRouter.ServeHTTP(record, req)
33+
34+
assert.Equal(t, http.StatusOK, record.Code)
35+
assert.Equal(t, want, record.Body.String())
1236
})
1337
}

0 commit comments

Comments
 (0)