vendredi 6 septembre 2019

Mocking functions within Go package functions

I am trying to mock an HTTP client that's being used within an API function call in my Golang 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)
    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.

How do you do something like this?

Aucun commentaire:

Enregistrer un commentaire