Kyoo
Kyoo

Reputation: 101

How to mock test with ` func(w http.ResponseWriter, r *http.Request) `

I got problem when I want to get the respond body from my mocking, currently I have create some mock like this :

func (m *MockCarService) GetCar(ctx context.Context, store store.Store, IDCar uint) (interface{}, error) {

    call := m.Called(ctx, store)
    res := call.Get(0)
    if res == nil {
        return nil, call.Error(1)
    }
    return res.(*models.Cars), call.Error(1)
}

Then I create handler_test.go like this :

func TestGetCar(t *testing.T) {

    var store store.Store

    car := &models.Cars{
        ID:          12345,
        BrandID:     1,
        Name:        "Car abc",
        Budget:      2000,
        CostPerMile: 4000,
        KpiReach:    6000,
    }

    mockService := func() *service.MockCarService {
        svc := &service.MockCarService{}
        svc.On("GetCar", context.Background(), car.ID).Return(car, nil)
        return svc
    }

    handlerGet := NewCarHandler(mockService())
    actualResponse := handlerGet.GetCar(store) 

    expected := `{"success":true,"data":[],"errors":[]}` 
    assert.Equal(t, expected+"\n", actualResponse)
}

What I got is some error (http.HandlerFunc)(0x165e020) (cannot take func type as argument)

I have no idea how to fix it. Since I'm using handler like this :

func (ah *CampaignHandler) GetCampaigns(store store.Store) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {  .....

Upvotes: 3

Views: 13845

Answers (1)

Kartavya Ramnani
Kartavya Ramnani

Reputation: 828

If you are making a HTTP call to an external service and wish to test that and get mock response, you can use httptest

http package in go comes with httptest to test all your external http call dependencies.

Please find an example here : https://golang.org/src/net/http/httptest/example_test.go

If this is not your usecase, it is better to use stubs and the way to do it can be found here : https://dev.to/jonfriesen/mocking-dependencies-in-go-1h4d

Basically, what is means is to use interface and have your own struct and stubbed function calls which will return the response you want.

If you want to add some syntactic sugar to your tests, you can use testify : https://github.com/stretchr/testify

Hope this helps.

Upvotes: 6

Related Questions