Mocking package function

Suppose I have a method

// makes an http request and returns string as result
func makeHttpRequest(url, method string) string, err {


func f1() {



Now when writing test for f1(), I want to mock the execution of makeHttpRequest();

What are recommended methods to do this?

1 Like


You should use polymorphism through interface or function argument and dependency injection. That means that thanks to interface or function argument you can change the effective implementation and dependency injection will allow you to change this implementation according your need. You can for example make your function f1 accept an interface declaring makeHttpRequest or a function and you change the implementation from an effective one to a mock when necessary. Have a nice day.

1 Like

Thank you @imatmati
I have seen this practice before. My only concern was do we change the way we implement just for testing?

Are these practices the recommended way to do in Go?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.