簡體   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