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

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”