Warm tip: This article is reproduced from serverfault.com, please click

How to mock external methods for unit testing

发布于 2020-11-30 18:05:34

I want to mock methods for testing in Go. I am unable to figure out any steps/pattern that is usually followed to mock.

Consider below code and help me out in understanding.

package fetchClient

client.go

type Client struct {
    URL     string
}

type ClientData struct {
    ID      string       
}

func (p *Client) GetURL(ID string) (*ClientData) {
    data := &ClientData{}
    //Some work to store client information into data struct and return it 
    return data
}

package fetchClientData

FetchData.go

// Function GetData that accepts a client ID as argument and returns client URL
func GetData(ID string) (*fetchClient.Client.URL) {
    param := (*Client).GetURL(ID) 
    return param
}

FetchData_test.go //Want to know how to mock as asked in below question.

Question: How to mock a fake GetURL function in FetchData_test.go file so that it does not call actual GetURL function in FetchData.go file, instead mock it.

Questioner
Pankaj Yadav
Viewed
0
Namor81 2020-12-01 04:36:18

There are two ways to resolve your problem, possibly. I can only make some assumptions based on the code that you have posted being quite minimal. But you wll either have to create the mocking library that implements your functions through http test or you could migrate your function calls into an interface to be used/consumed so that you can use the MockGen capability within GoMock. the latter is probably going to be cleaner and closer to Go Best Practices.

Look over their documentation. https://github.com/golang/mock