模拟在Golang Http处理程序中调用的功能

I have a function need to be tested, which looks like this:

func parmHandler(w http.ResponseWriter, r *http.Request) {
   ...
   data, err = backenddb_call(r *http.Request)
   ...
   return
}


function backenddb_call(r *http.Request) (data []Data, err error){
   parm := r.URL.Query().Get(parm)
   //Get Data from DB for parm 
   ...
   return
}

In this HTTP handler case, I cannot modify the parmHandler arguments and add a helper interface argument to help with mocking. How can I mock backenddb_call to return different responses?

You could have a function which returns your handler, which you pass the backenddb_call as an argument to:

https://play.golang.org/p/aSMxeEgJL8U

func GetHandler(fn func (r *http.Request) ([]Data, error)) http.Handler {
    return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
        data, err := fn(r)
        fmt.Println(data, err)
    })
}

Then, when you create it:

http.HandleFunc("/test", GetHandler(backenddb_call))

and to test it you can just pass in a different call:

GetHandler(func (r *http.Request) ([]Data, error) {
    fmt.Println("Mock")
    return []Data{"This", "Is", "A", "Fake", "Response"}, nil
})