gin golang example test

Example 1: go gin unit test

follow this my tutorial for simple implementation, easy to undestand

https://github.com/restuwahyu13/gin-unit-testing

Example 2: go gin unit test

// main.go
package main

import (
	"net/http"

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

func HelloWorld(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"hello": "world",
	})
}

func main() {
	router := gin.Default()
	router.GET("/", HelloWorld)
	router.Run()
}


// main_test.go
package main

import (
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func TestHelloWorld1(t *testing.T) {

	w := httptest.NewRecorder()
	gin.SetMode(gin.TestMode)
	c, _ := gin.CreateTestContext(w)
	HelloWorld(c)

	t.Run("get json data", func(t *testing.T) {
		assert.Equal(t, 200, w.Code)
	})
}

func TestHelloWorld2(t *testing.T) {

	w := httptest.NewRecorder()
	router := gin.Default()
	gin.SetMode(gin.TestMode)

	router.GET("/", HelloWorld)

	t.Run("get json data", func(t *testing.T) {
		assert.Equal(t, 200, w.Code)
	})
}

Tags:

Misc Example