I am trying to mock an HTTP client that's being used within an API function call in my Go code.
import (
"internal.repo/[...]/http"
"encoding/json"
"strings"
"github.com/stretchr/testify/require"
)
func CreateResource(t *testing.T, url string, bodyReq interface{}, username string, password string, resource string) []byte {
bodyReqJSON, err := json.Marshal(bodyReq)
if err != nil {
panic(err)
}
headers := make(map[string]string)
headers["Content-Type"] = "application/json"
logger.Logf(t, "*************************** CREATE a temporary test %s ***************************", resource)
// this func below should be mocked
statusCode, body := http.POST(t, url, bodyReqJSON, headers, username, password)
require.Equal(t, statusCode, 201, "******ERROR!! A problem occurred while creating %s. Body: %s******", resource, strings.TrimSpace(string(body)))
return body
}
I'd like to mock my http.POST
function that it's part of an internal HTTP package so that I do not need to actually make the online call, and isolate the test offline.
Is there an alternative way to dependency-inject a mock structure that implements an hypothetical HTTP interface?
How would you do something like this?