如何在Go中正确测试控制器类

如何在Go中正确测试控制器类,go,gomock,Go,Gomock,我使用gomock生成一个业务层并模拟它的方法和结果。到目前为止,我还不能通过测试,它说“想要”和“得到”的值是不同的 我正在将对象的json表示形式传递给strings.NewReader,“Want”带有一个值“等于{{…”,这可能是问题所在 package product import ( //... ) var ( productBody = `{"seller":{"id":"Foo"},"sku":"kj1293lkxpto","gtin":"789494950

我使用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>}}

包装产品
进口(
//...
)
变量(
productBody=`{“卖方”:{“id”:“Foo”},“sku”:“kj1293lkxpto”,“gtin”:“7894949501280”,“名称”:“Foo”,“描述”:“Bar”,“legacyInfo”:{“id”:1021,“数字”:4,“线”:{“id”:1,“系列”:{“id”:3},“情况”:“EC”},“ncm”:612522332,“原产地”:0,“单位”:“千克”,“技术细节”:{“体积”:1},“重量”:0.56,“高度”:100,“宽度”:100;“长度”:172}{“id”:1,“描述”:“活动”}`
mockProduct=model.Product{
卖家:model.Seller{ID:“Foo”},
Sku:“kj1293lkxpto”,
Gtin:“78949501280”,
姓名:"富",,
说明:“酒吧”,
LegacyInfo:model.LegacyInfo{
ID:1021,
数字:4,
行:模型行{
ID:1,
家庭:模特。家庭{
ID:3,
},
},
情况:“欧共体”,
},
新墨西哥州:612522332,
来源:0,
单位:千克,
技术细节:model.TechnicalDetails{
体积:模型。体积{
数量:1,
},
重量:0.56,
身高:100,
宽度:172.96,
长度:100,
},
状态:模型。状态{
ID:1,
描述:“活动”,
},
}
e*echo.echo
c.背景
请求*http.Request
rec*httptest.ResponseRecorder
)
func TestCreate(t*testing.t){
ctrl:=gomock.NewController(t)
延迟ctrl.Finish()
e=echo.New()
e、 Validator=middleware.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(请求、记录)
mockHandler:=mock_product.NewMockIHandler(ctrl)
mockHandler.EXPECT().Save(mockProduct.Return(&mockProduct,nil)//第37行
控制器:=新控制器(mockHandler)
控制器。创建(c)
}
//--控制器,开始
包装产品
进口(
//...
)
func NewController(handler IHandler)*控制器{
返回&控制器{handler}
}
func(c*控制器)创建(ctx echo.Context)错误{
// ...
}
//--汉德勒,走
//服务
包装产品
类型IHandler接口{
保存(product*model.product)(savedProduct*model.product,错误)
}
func(h*处理程序)保存(产品*模型.product)(保存的产品*模型.product,错误){
//...
}
//--product.go
包模型
类型产品结构{
ID字符串`json:“ID,省略空”`
Seller`json:“Seller,省略空”`
Sku字符串`json:“Sku,省略空”`
Gtin字符串`json:“Gtin,省略空”`
名称字符串`json:“名称,省略为空”`
描述字符串`json:“描述,省略空”`
LegacyInfo LegacyInfo`json:“LegacyInfo,省略为空”`
Ncm int64`json:“Ncm,省略空”`
Origin int`json:“Origin,省略空”`
单位字符串`json:“单位,省略为空”`
TechnicalDetails TechnicalDetails`json:“TechnicalDetails,省略为空”`
Status Status`json:“Status,empty”`
CreatedAt Date`json:“CreatedAt,省略空”`
UpdatedAt`json:“UpdatedAt,省略空”`
}```
应在/foo/bar/controller\u test.go:37处调用,但与索引0处的参数不匹配。
获得:&{Foo}kj1293lkxpto 78949501280 Foo Bar{10214{1{3}EC}612522332 0 kg{1}0.56 100 172.96 100}{1 active}{
想要:等于{{Foo}kj1293lkxpto 78949501280 Foo Bar{10214{1{3}EC}612522332 0 kg{1}0.56 100 172.96 100}{1 active}{
编辑:

我做了@bigdege提到的事

    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}}
func TestCreate(t*testing.t){
ctrl:=gomock.NewController(t)
延迟ctrl.Finish()
b、 err:=json.Marshal(&mockProduct)
fmt.Println(错误)
格式打印项次(字符串(b))
e=echo.New()
e、 Validator=middleware.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(请求、记录)
mockHandler:=mock_product.NewMockIHandler(ctrl)
mockHandler.EXPECT().Save(&mockProduct).Return(&mockProduct,nil)
控制器:=新控制器(mockHandler)
控制器。创建(c)
}
{“id”:“123”,“卖方”:{“id”:“Foo”},“sku”:“kj1293lkxpto”,“gtin”:“7894949501280”,“名称”:“Foo”,“描述”:“Bar”,“legacyInfo”:{“id”:1021,“数字”:4,“行”:{“id”:1,“系列”:{“id”:3},“情况”:“EC”},“ncm”:612522332,“单位”:“千克”,“技术细节”:{“体积”:{“数量”:1},“重量”:0.56,“高度”:100,“宽度”:172.96,“长度”:100},“描述”:“活动”},“创建日期”:“03-09-2019 00:41:56”,“更新日期”:“03-09-2019 00:41:56”}
---失败:TestCreate(0.00s)
/home/ivo/workspace/GoNew/deckard writer/api/routes/product/controller.go:41:在/home/ivo/workspace/GoNew/deckard writer/api/routes/product/mock/handler.Save([0xc0003aa0f0])处意外调用*mock_product.MockIHandler.Save([0xc0003aa0f0])。go:39因为:
在/home/ivo/Workspaces/GoNew/deckard writer/api/routes/product/controller_test处预期调用。go:43与索引0处的参数不匹配。
得到:&{123{Foo}kj1293lkxpto 78949501280 Foo Bar{10214{1{3}}EC}