jjzjj

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

coder 2024-07-13 原文

我正在使用 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/

有关go - 如何在 Go 中正确测试 Controller 类的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  6. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  7. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  8. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

随机推荐