Home > Back-end >  Golang - Mock a function for temporal test
Golang - Mock a function for temporal test

Time:08-20

Basically I have a 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"`
}

which is called in my temporal activity.

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

and my activity returns the id of this uploaded file

return file.FileRecordId, nil

Now I want to try to test my activity, but for this i have to input the expected id that gets returned. I thought about mocking the upload function so it will return the file with a id I want it to have, so I can isolate the test to only test my activity, I expect the upload function is working properly so no need to test there.

What is the best approach?

CodePudding user response:

I would say the easiest way around it is to declare an Interface for your target and use a mock package to generate it like gomock

Instruction is given to generate the mock easily

(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.
      }
  • Related