Skip to content

Instantly share code, notes, and snippets.

View nidhi-canopas's full-sized avatar

nidhi-canopas

View GitHub Profile
package models
import (
"gorm.io/gorm"
)
type User struct {
gorm.Model
ID int
Name string
package controllers
import (
"errors"
"gorm-test/database"
"gorm-test/models"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
func MockJsonDelete(c *gin.Context, params gin.Params) {
c.Request.Method = "DELETE"
c.Request.Header.Set("Content-Type", "application/json")
c.Set("user_id", 1)
c.Params = params
}
func MockJsonPut(c *gin.Context, content interface{}, params gin.Params) {
c.Request.Method = "PUT"
c.Request.Header.Set("Content-Type", "application/json")
c.Set("user_id", 1)
c.Params = params
jsonbytes, err := json.Marshal(content)
if err != nil {
panic(err)
}
func MockJsonPost(c *gin.Context, content interface{}) {
c.Request.Method = "POST"
c.Request.Header.Set("Content-Type", "application/json")
c.Set("user_id", 1)
jsonbytes, err := json.Marshal(content)
if err != nil {
panic(err)
}
// code
func GetUserId(c *gin.Context) {
fmt.Println(c.Query("foo")) //will print "bar" while running test
fmt.Println(c.Param("id")) // will print "1" while running test
id, _ := strconv.Atoi(c.Param("id"))
c.JSON(http.StatusOK, id)
}
// mock gin context
func GetTestGinContext() *gin.Context {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(w)
ctx.Request = &http.Request{
Header: make(http.Header),
URL: &url.URL{},
}
func MockJsonGet(c *gin.Context) {
c.Request.Method = "GET"
c.Request.Header.Set("Content-Type", "application/json")
c.Set("user_id", 1)
// set path params
c.Params = []gin.Param{
{
Key: "id",
Value: "1",
func GetTestGinContext() *gin.Context {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(w)
ctx.Request = &http.Request{
Header: make(http.Header)
}
return ctx
func HelloWorld(c *gin.Context) {
text := c.DefaultQuery("txt", "Hey Go dev!!")
c.JSON(http.StatusOK, gin.H{"greeting": text})
}
// endpoint
r.GET("/hello", HelloWorld)