go - 如何在 Go 中正确测试 Controller 类

标签 go gomock

我正在使用 gomock 生成业务层并模拟其方法结果。到目前为止,我无法让测试通过,它说“想要”和“得到”的值不同

我正在将对象的 json 表示形式传递给 strings.NewReader,而“Want”的值“等于 { { ...”,这可能是问题所在。


package product

import (
    //...
)

var (
    productBody = `{"seller":{"id":"Foo"},"sku":"kj1293lkxpto","gtin":"7894949501280","name":"Foo","description":"Bar","legacyInfo":{"id":1021,"digit":4,"line":{"id":1,"family":{"id":3}},"situation":"EC"},"ncm":612522332,"origin":0,"unit":"kg","technicalDetails":{"volume":{"quantity":1},"weight":0.56,"height":100,"width":172.96,"length":100},"status":{"id": 1,"description":"active"}}`
        mockProduct  = model.Product{
        Seller:      model.Seller{ID: "Foo"},
        Sku:         "kj1293lkxpto",
        Gtin:        "7894949501280",
        Name:        "Foo",
        Description: "Bar",
        LegacyInfo: model.LegacyInfo{
            ID:    1021,
            Digit: 4,
            Line: model.Line{
                ID: 1,
                Family: model.Family{
                    ID: 3,
                },
            },
            Situation: "EC",
        },
        Ncm:    612522332,
        Origin: 0,
        Unit:   "kg",
        TechnicalDetails: model.TechnicalDetails{
            Volume: model.Volume{
                Quantity: 1,
            },
            Weight: 0.56,
            Height: 100,
            Width:  172.96,
            Length: 100,
        },
        Status: model.Status{
            ID:          1,
            Description: "active",
        },
    }
    e   *echo.Echo
    c   echo.Context
    req *http.Request
    rec *httptest.ResponseRecorder
)

func TestCreate(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    e = echo.New()
    e.Validator = middlewares.NewCustomValidator()
    rec = httptest.NewRecorder()
    req = httptest.NewRequest(http.MethodPost, "/v1/foo/bar", strings.NewReader(productBody))
    req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
    c = e.NewContext(req, rec)

    mockHandler := mock_product.NewMockIHandler(ctrl)

    mockHandler.EXPECT().Save(mockProduct).Return(&mockProduct, nil) // line 37

    controller := NewController(mockHandler)

    controller.Create(c)
}

// -- controller.go
package product

import (
    //...
)

func NewController(handler IHandler) *Controller {
    return &Controller{handler}
}

func (c *Controller) Create(ctx echo.Context) error {
// ...
}

// -- handler.go
// service
package product

type IHandler interface {
    Save(product *model.Product) (savedProduct *model.Product, err error)
}

func (h *Handler) Save(product *model.Product) (savedProduct *model.Product, err error) {
//...
}

// -- product.go
package model

type Product struct {
    ID               string           `json:"id,omitempty"`
    Seller           Seller           `json:"seller,omitempty"  `
    Sku              string           `json:"sku,omitempty"  `
    Gtin             string           `json:"gtin,omitempty"`
    Name             string           `json:"name,omitempty"`
    Description      string           `json:"description,omitempty"`
    LegacyInfo       LegacyInfo       `json:"legacyInfo,omitempty"`
    Ncm              int64            `json:"ncm,omitempty"`
    Origin           int              `json:"origin,omitempty"`
    Unit             string           `json:"unit,omitempty"`
    TechnicalDetails TechnicalDetails `json:"technicalDetails,omitempty"`
    Status           Status           `json:"status,omitempty"`
    CreatedAt        Date             `json:"createdAt,omitempty"`
    UpdatedAt        Date             `json:"updatedAt,omitempty"`
}```


Expected call at /foo/bar/controller_test.go:37 doesn't match the argument at index 0.
        Got: &{ {Foo} kj1293lkxpto 7894949501280 Foo Bar {1021 4 {1 {3}} EC} 612522332 0 kg {{1} 0.56 100 172.96 100} {1 active} {<nil>} {<nil>}}
        Want: is equal to { {Foo} kj1293lkxpto 7894949501280 Foo Bar {1021 4 {1 {3}} EC} 612522332 0 kg {{1} 0.56 100 172.96 100} {1 active} {<nil>} {<nil>}}

编辑:

我做了@bigpigeon 提到的

    func TestCreate(t *testing.T) {
        ctrl := gomock.NewController(t)
        defer ctrl.Finish()

        b, err := json.Marshal(&mockProduct)
        fmt.Println(err)
        fmt.Println(string(b))

        e = echo.New()
        e.Validator = middlewares.NewCustomValidator()
        rec = httptest.NewRecorder()
        req = httptest.NewRequest(http.MethodPost, "/v1/foo/bar", strings.NewReader(string(b)))
        req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
        c = e.NewContext(req, rec)

        mockHandler := mock_product.NewMockIHandler(ctrl)

        mockHandler.EXPECT().Save(&mockProduct).Return(&mockProduct, nil)

        controller := NewController(mockHandler)

        controller.Create(c)
    }

    <nil>
    {"id":"123","seller":{"id":"Foo"},"sku":"kj1293lkxpto","gtin":"7894949501280","name":"Foo","description":"Bar","legacyInfo":{"id":1021,"digit":4,"line":{"id":1,"family":{"id":3}},"situation":"EC"},"ncm":612522332,"unit":"kg","technicalDetails":{"volume":{"quantity":1},"weight":0.56,"height":100,"width":172.96,"length":100},"status":{"id":1,"description":"active"},"createdAt":"03-09-2019 00:41:56","updatedAt":"03-09-2019 00:41:56"}
    --- FAIL: TestCreate (0.00s)
        /home/ivo/Workspaces/GoNew/deckard-writer/api/routes/product/controller.go:41: Unexpected call to *mock_product.MockIHandler.Save([0xc0003aa0f0]) at /home/ivo/Workspaces/GoNew/deckard-writer/api/routes/product/mock/handler.go:39 because: 
            Expected call at /home/ivo/Workspaces/GoNew/deckard-writer/api/routes/product/controller_test.go:43 doesn't match the argument at index 0.
            Got: &{123 {Foo} kj1293lkxpto 7894949501280 Foo Bar {1021 4 {1 {3}} EC} 612522332 0 kg {{1} 0.56 100 172.96 100} {1 active} {2019-09-03 00:41:56 +0000 UTC} {2019-09-03 00:41:56 +0000 UTC}}
            Want: is equal to &{123 {Foo} kj1293lkxpto 7894949501280 Foo Bar {1021 4 {1 {3}} EC} 612522332 0 kg {{1} 0.56 100 172.96 100} {1 active} {2019-09-03 00:41:56.733635373 -0300 -03 m=+0.003845944} {2019-09-03 00:41:56.733635557 -0300 -03 m=+0.003846109}}

同样的结果

最佳答案

我在@big pigeon 的帮助下解决了。 问题是我有一个我第一次没有放置的时间属性,但是在使 json marshal 工作之后我又放置了它,我可以准确地看到“想要”和“得到”之间的区别

关于go - 如何在 Go 中正确测试 Controller 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57763839/

相关文章:

testing - 哪个目录放模拟?

unicode - 我需要 unicode 来识别不同的书写系统吗

go mod 找不到依赖项的版本 v0.0.0-00010101000000-000000000000

unit-testing - 在 Go 单元测试中使用两个不同的模拟

go - 由于未接来电而导致测试中止

unit-testing - 如何比较/匹配模拟中的闭包?

unit-testing - 测试和模拟一个不返回任何值的函数

go - 通过函数分配Golang

string - 不可变字符串和指针地址

function - 重新分配指针函数参数