简体   繁体   中英

How to mock external methods for unit testing

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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