Answers for "gin http test"

0

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)
	})
}
Posted by: Guest on April-02-2021
0

gin http test

library for http testing for gin framework

https://github.com/restuwahyu13/go-supertest
Posted by: Guest on May-06-2021
0

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
}
Posted by: Guest on April-30-2021

Browse Popular Code Answers by Language