gin http test example

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)
	})
}

Example 3: gin http testing custom

package util

import (
	"bytes"
	"encoding/binary"
	"net/http"
	"net/http/httptest"

	"github.com/sirupsen/logrus"
)

func HttpTestRequest(method, url string, payload []byte) (*httptest.ResponseRecorder, *http.Request) {

	request := make(chan *http.Request, 1)
	errors := make(chan error, 1)

	if binary.Size(payload) > 0 {
		req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
		request <- req
		errors <- err
	} else {
		req, err := http.NewRequest(method, url, nil)
		request <- req
		errors <- err
	}

	if <-errors != nil {
		logrus.Fatal(<-errors)
	}

	rr := httptest.NewRecorder()

	return rr, <-request
}

Tags:

C Example