15

我正在使用 Gin 框架编写一个 REST API。但是我在测试我的控制器和研究 TDD 和 Mock 时遇到了麻烦。我试图将 TDD 和 Mock 应用于我的代码,但我做不到。

我创建了一个非常精简的测试环境并尝试创建一个控制器测试。如何为 Gin.Context 创建 Mock?

这是我的示例代码:

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]
}

我的测试示例:

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

4 回答 4

35

Gin 提供了创建测试上下文的选项,您可以根据需要使用它: https ://godoc.org/github.com/gin-gonic/gin#CreateTestContext

像那样:

c, _ := gin.CreateTestContext(httptest.NewRecorder())
于 2018-04-06T20:07:29.860 回答
16

这是我如何模拟上下文,添加参数,在函数中使用它,然后在有非 200 响应时打印响应字符串的示例。

gin.SetMode(gin.TestMode)

w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Params = []gin.Param{gin.Param{Key: "k", Value: "v"}}

foo(c)

if w.Code != 200 {
    b, _ := ioutil.ReadAll(w.Body)
    t.Error(w.Code, string(b))
}

于 2019-05-17T05:13:00.370 回答
12

为了获得*gin.Context可以测试的实例,您需要一个模拟 HTTP 请求和响应。创建它们的一种简单方法是使用net/httpandnet/http/httptest包。根据您链接的代码,您的测试将如下所示:

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
)

func TestControllerGetAll(t *testing.T) {

    // Switch to test mode so you don't get such noisy output
    gin.SetMode(gin.TestMode)

    // Setup your router, just like you did in your main function, and
    // register your routes
    r := gin.Default()
    r.GET("/users", GetUsers)

    // Create the mock request you'd like to test. Make sure the second argument
    // here is the same as one of the routes you defined in the router setup
    // block!
    req, err := http.NewRequest(http.MethodGet, "/users", nil)
    if err != nil {
        t.Fatalf("Couldn't create request: %v\n", err)
    }

    // Create a response recorder so you can inspect the response
    w := httptest.NewRecorder()

    // Perform the request
    r.ServeHTTP(w, req)

    // Check to see if the response was what you expected
    if w.Code != http.StatusOK {
        t.Fatalf("Expected to get status %d but instead got %d\n", http.StatusOK, w.Code)
    }
}

虽然您可以创建一个 mock *gin.Context,但使用上面的方法可能更容易,因为它会像实际请求一样执行和处理您的请求。

于 2017-01-19T19:02:22.127 回答
11

如果将问题简化为“如何为函数参数创建模拟?” 答案是:使用接口而不是具体类型。

type Context struct是一个具体的类型文字,而 Gin 没有提供适当的接口。但是你可以自己声明。由于您只使用JSON来自您的方法,Context因此您可以声明非常简单的接口:

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

并使用JSONertype 代替Context输入所有期望Context作为参数的函数:

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

现在很容易测试

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()
    }
}

示例尽可能简单。

还有一个很贴切的问题

于 2017-01-20T11:01:10.743 回答