Skip to content

Unable to Mock Responses with Custom http.Client and Transport #154

@battlecook

Description

@battlecook

Thank you for creating a good package. I am using a custom http client. If I write the test code as below, it is working good.

func createHttpClient() *http.Client {
	httpClient := &http.Client{}
	return httpClient
}

func doHttp(cli *http.Client, addr string) string {
	reqUrl, _ := url.Parse(addr)
	req := &http.Request{
		Method: http.MethodGet,
		URL:    reqUrl,
	}
	res, err := cli.Do(req)
	if err != nil {
		panic(err)
	}

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	return string(body)
}

func TestHttpMock(t *testing.T) {

	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	addr := "http://example/foo"
	httpmock.RegisterResponder(http.MethodGet, addr,
		func(req *http.Request) (*http.Response, error) {
			return httpmock.NewStringResponse(http.StatusOK, "bar"), nil
		},
	)

	cli := createHttpClient()

	ret := doHttp(cli, addr)

	assert.Equal(t, "bar", ret)
}

However, I confirmed that I cannot receive a mock response if I add the transport option to createHttpClient as shown below.

func createHttpClient() *http.Client {
	httpClient := &http.Client{
		Transport: &http.Transport{},
	}
	return httpClient
}

Is there a way to make it work even if I add the transport option?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions