steinfletcher / apitest

A simple and extensible behavioural testing library for Go. You can use api test to simplify REST API, HTTP handler and e2e tests.
https://apitest.dev
MIT License
778 stars 55 forks source link

Using mocks with custom HTTP client #144

Closed azhinu closed 8 months ago

azhinu commented 8 months ago

Is it possible to mock a custom HTTP client? I'm trying to use Resty, but no success. For example, Gock allow using custom HTTP client by setting gock.DefaultTransport for the client, or by using gock.InterceptClient(client). Is there a way to use apitest mocks with clients like Resty?

azhinu commented 8 months ago

Okay, I found that to use standalone mocks, I should to add HttpClient(client) to standalone mock builder.

    resetTransport := apitest.NewStandaloneMocks(
        apitest.NewMock().
        Get("/user-api").
        RespondWith().
        Body(`{"name": "jon", "id": "1234"}`).
        Status(http.StatusOK).
        End(),
    ).HttpClient(client.GetClient()).End()
    defer resetTransport()

And to use with apitest, I should to add HttpClient(client) to apitest builder.

    apitest.New().
        Mocks(getUserMock).
        HttpClient(client.GetClient()).
        Handler(myHandler()).
        Get("/user").
        Expect(t).
        Status(http.StatusOK).
        Body(`{"name": "jon", "id": "1234"}`).
        End()

In examples above client is *Resty.Client