Unit Test with Gin-Gonic

Here my controller using gin context and when I use Unit Test all test are KO

package controllers

import "github.com/gin-gonic/gin"

// HealthCheck godoc
// @Summary     Show the status of server.
// @Description get the status of server.
// @Tags        HealthCheck
// @Accept      */*
// @Produce     json
// @Success     200 {object} map[string]interface{}
// @Router      /healthcheck [get]
func HealthCheck(c *gin.Context) {
	res := map[string]interface{}{
		"data": "Server is up and running",
	}
	c.JSON(200, gin.H{
		"data": res,
	})
}

// @BasePath /api/v1

// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags        Ping
// @Accept      json
// @Produce     json
// @Success     200 {string} Pong
// @Router      /ping [get]
func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

My UT

package main

import (
	"go-jwwt/initializers"
	"net/http"
	"net/http/httptest"
	"testing"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func TestHealthCheck(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router  := gin.Default()

	w := httptest.NewRecorder()

	req, _  := http.NewRequest(http.MethodGet, "/healthcheck", nil)
	router.ServeHTTP(w, req)
	//Assertion
	assert.Equal(t, http.StatusOK, w.Code)
	//assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, "Server is up and running", w.Body.String())
}



func TestPing(t *testing.T) {
	
	gin.SetMode(gin.TestMode)
	router  := gin.Default()


	w := httptest.NewRecorder()



	req, _  := http.NewRequest(http.MethodGet, "/ping", nil)
	router.ServeHTTP(w, req)
	//Assertion
	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, "pong", w.Body.String())
}


File main.go

func main() {
    
   r := gin.Default()
	v1 := r.Group(os.Getenv("API_DEFAULT"))
	{
		v1.GET("/healthcheck", controllers.HealthCheck)
		v1.GET("/ping", controllers.Ping)
	}
	
	r.Run() // listen and serve on 0.0.0.0:8080
}

What I have omitted in my UT ?

Is there a problem when you try running the tests or are you asking if there is anything else that the tests should check for?

Yes : I have an error




Yes : I have an error
```go
=== RUN   TestHealthCheck
[GIN] 2022/07/30 - 15:42:17 | 404 |            0s |                 | GET      ""/api/v1/healthcheck"
    main_test.go:29:
                Error Trace:    myPath\go-jwt\main_test.go:29
                Error:          Not equal:
                                expected: 200
                                actual  : 404
                Test:           TestHealthCheck
    main_test.go:31:
                Error Trace:    myPath\go-jwt\main_test.go:31
                Error:          Not equal:
                                expected: "Server is up and running"
                                actual  : "404 page not found"

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -1 +1 @@
                                -Server is up and running
                                +404 page not found
                Test:           TestHealthCheck
--- FAIL: TestHealthCheck (0.00s)
=== RUN   TestPing
[GIN] 2022/07/30 - 15:42:17 | 404 |            0s |                 | GET      "/api/v1/ping"
    main_test.go:49:
                Error Trace:    myPath\go-jwt\main_test.go:49
                Error:          Not equal:
                                expected: 200
                                actual  : 404
                Test:           TestPing
    main_test.go:50:
                Error Trace:    myPath\go-jwt\main_test.go:50
                Error:          Not equal:
                                expected: "pong"
                                actual  : "404 page not found"

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -1 +1 @@
                                -pong
                                +404 page not found
                Test:           TestPing
--- FAIL: TestPing (0.00s)
FAIL

Is there a problem of context cause when I run the main.go this endPoints are responding well ?
Is there something I omit in my tests

Thanks for posting the error; I understand now.

The first problem is that you haven’t told the router about your HealthCheck and Ping controllers, so Gin is performing the default behavior of returning a 404. I’ve never used Gin before, but I looked around on their site and it seems like what you want is to configure those routes with the router’s GET function:

// ...
router := gin.Default()
router.GET("/healthcheck", controllers.HealthCheck)
router.GET("/ping", controllers.Ping)

That will get you past the 404.

I solve this by modify as expected in their Unit Test :



package main

import (
	"go-jwwt/initializers"

	"net/http"
	"net/http/httptest"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/gin-gonic/gin"
)

func TestHealthCheck(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := setUpRouter()
	w := httptest.NewRecorder()

	wanted :=`{"data":{"data":"Server is up and running"}}`

	req, _  := http.NewRequest(http.MethodGet, "/api/v1/healthcheck", nil)
	router.ServeHTTP(w, req)
	//Assertion
	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, wanted, w.Body.String())
}



func TestPing(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := setUpRouter()
	w := httptest.NewRecorder()

	wanted :=`{"message":"pong"}`

	req, _  := http.NewRequest(http.MethodGet, "/api/v1/ping", nil)
	router.ServeHTTP(w, req)
	//Assertion
	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, wanted, w.Body.String())
}


And the router function


func setUpRouter()  *gin.Engine {
	r := gin.Default()
	v1 := r.Group(os.Getenv("API_DEFAULT"))
	{
		// Routes
		v1.GET("/healthcheck", controllers.HealthCheck)
		v1.GET("/ping", controllers.Ping)
	}

	return r 
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.