繁体   English   中英

Golang - 模拟 function 进行时间测试

[英]Golang - Mock a function for temporal test

基本上我有一个uploadFile function:

func UploadImage(fileContent []byte, fileName string, contentType string, fileRecordType string, id string, fileRecordId string, format string) (*dto.FileUpload, error)

type FileUpload struct {
    FileId       string `json:"id"`
    FileName     string `json:"fileName"`
    FileSize     int32  `json:"fileSize"`
    FileRecordId string `json:"fileRecordId"`
    ContentType  string `json:"contentType"`
}

这在我的时间活动中被称为。

file, err := utils.UploadImage(newImage, "convImgFrom_"+param.FileRecordId, "image/"+utils.GetImageFormat(param.Format), "IMAGE", uuid.New(), uuid.New(), utils.GetImageFormat(param.Format)) 

我的活动返回这个上传文件的 id

return file.FileRecordId, nil

现在我想尝试测试我的活动,但为此我必须输入返回的预期 ID。 我考虑过 mocking 上传 function 所以它会返回带有我希望它拥有的 id 的文件,所以我可以隔离测试只测试我的活动,我希望上传 ZC1C425268E68385D1AB507F14 正常工作所以不需要测试。

最好的方法是什么?

我想说最简单的方法是为您的目标声明一个Interface并使用模拟 package 像gomock一样生成它

给出了轻松生成模拟的说明

(1) Define an interface that you wish to mock.
      type MyInterface interface {
        SomeMethod(x int64, y string)
      }
(2) Use mockgen to generate a mock from the interface.
(3) Use the mock in a test:
      func TestMyThing(t *testing.T) {
        mockCtrl := gomock.NewController(t)
        defer mockCtrl.Finish()

        mockObj := something.NewMockMyInterface(mockCtrl)
        mockObj.EXPECT().SomeMethod(4, "blah")
        // pass mockObj to a real object and play with it.
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM