Mocking package function


(Sabbir Manandhar) #1

Suppose I have a method

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

}

func f1() {


makeHttpRequest(…);


}

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

What are recommended methods to do this?


(Ivan Matmati) #2

Hi,

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.


(Sabbir Manandhar) #3

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?


(system) closed #4

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