dongqian0763 2017-01-19 13:28
浏览 482
已采纳

在Golang中制作模拟gin.Context

I'm writing a REST API using Gin framework. But I was faced a trouble testing my controllers and researching TDD and Mock. I tried to apply TDD and Mock to my code but I could not.

I created a very reduced test environment and tried to create a controller test. How do I create a Mock for Gin.Context?

Here's my example code:

package main

import (
    "strconv"
    "github.com/gin-gonic/gin"
)

// MODELS
type Users []User
type User struct {
    Name string `json"name"`
}


func main() {
    r := gin.Default()

    r.GET("/users", GetUsers)
    r.GET("/users/:id", GetUser)

    r.Run(":8080")
}

// ROUTES
func GetUsers(c *gin.Context) {
    repo := UserRepository{}
    ctrl := UserController{}

    ctrl.GetAll(c, repo)
}

func GetUser(c *gin.Context) {
    repo := UserRepository{}
    ctrl := UserController{}

    ctrl.Get(c, repo)
}

// CONTROLLER
type UserController struct{}

func (ctrl UserController) GetAll(c *gin.Context, repository UserRepositoryIterface) {
    c.JSON(200, repository.GetAll())
}

func (ctrl UserController) Get(c *gin.Context, repository UserRepositoryIterface) {

    id := c.Param("id")

    idConv, _ := strconv.Atoi(id)

    c.JSON(200, repository.Get(idConv))
}

// REPOSITORY
type UserRepository struct{}
type UserRepositoryIterface interface {
    GetAll() Users
    Get(id int) User
}

func (r UserRepository) GetAll() Users {
    users := Users{
        {Name : "Wilson"},
        {Name : "Panda"},
    }

    return users
}

func (r UserRepository) Get(id int) User {
    users := Users{
        {Name : "Wilson"},
        {Name : "Panda"},
    }

    return users[id-1]
}

My test example:

package main

import(
    "testing"
    _ "github.com/gin-gonic/gin"
)

type UserRepositoryMock struct{}

func (r UserRepositoryMock) GetAll() Users {
    users := Users{
        {Name : "Wilson"},
        {Name : "Panda"},
    }

    return users
}

func (r UserRepositoryMock) Get(id int) User {
    users := Users{
        {Name : "Wilson"},
        {Name : "Panda"},
    }

    return users[id-1]
}


// TESTING REPOSITORY FUNCTIONS
func TestRepoGetAll(t *testing.T) {

    userRepo := UserRepository{}

    amountUsers := len(userRepo.GetAll())

    if amountUsers != 2 {
        t.Errorf("Esperado %d, recebido %d", 2, amountUsers)
    }
}

func TestRepoGet(t *testing.T) {

    expectedUser := struct{
        Name string
    }{
        "Wilson",
    }

    userRepo := UserRepository{}

    user := userRepo.Get(1)

    if user.Name != expectedUser.Name {
        t.Errorf("Esperado %s, recebido %s", expectedUser.Name, user.Name)
    }
}

/* HOW TO TEST CONTROLLER?
func TestControllerGetAll(t *testing.T) {
    gin.SetMode(gin.TestMode)
    c := &gin.Context{}
    c.Status(200)
    repo := UserRepositoryMock{}
    ctrl := UserController{}

    ctrl.GetAll(c, repo)
}
*/
  • 写回答

4条回答 默认 最新

  • duanchu7271 2017-01-20 11:01
    关注

    If to reduce the question to "How to create mock for a function argument?" the answer is: use interfaces not concrete types.

    type Context struct is a concrete type literal and Gin doesn't provide appropriate interface. But you can declare it by yourself. Since you are using only JSON method from Context you can declare extra-simple interface:

    type JSONer interface {
        JSON(code int, obj interface{})
    }
    

    And use JSONer type instead Context type in all your functions which expect Context as argument:

    /* Note, you can't declare argument as a pointer to interface type,
       but when you call it you can pass pointer to type which
       implements the interface.*/
    func GetUsers(c JSONer) {
        repo := UserRepository{}
        ctrl := UserController{}
    
        ctrl.GetAll(c, repo)
    }
    
    func GetUser(c JSONer) {
        repo := UserRepository{}
        ctrl := UserController{}
    
        ctrl.Get(c, repo)
    }
    
    func (ctrl UserController) GetAll(c JSONer, repository UserRepositoryIterface) {
        c.JSON(200, repository.GetAll())
    }
    
    func (ctrl UserController) Get(c JSONer, repository UserRepositoryIterface) {
    
        id := c.Param("id")
    
        idConv, _ := strconv.Atoi(id)
    
        c.JSON(200, repository.Get(idConv))
    }
    

    And now it is easy to test

    type ContextMock struct {
        JSONCalled bool
    }
    
    func (c *ContextMock) JSON(code int, obj interface{}){
        c.JSONCalled = true
    }
    
    func TestControllerGetAll(t *testing.T) {
        gin.SetMode(gin.TestMode)
        c := &ContextMock{false}
        c.Status(200)
        repo := UserRepositoryMock{}
        ctrl := UserController{}
    
        ctrl.GetAll(c, repo)
    
        if c.JSONCalled == false {
            t.Fail()
        }
    }
    

    Example simple as possible.

    There is another question with a close sense

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器