unit-testinggotestingmockinggo-gin

Make mock 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)
}
*/

Solution

  • 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