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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?