3

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) { ..... 
3
  • 2
    I don't see any line in the quoted code that could generate that error, and your quoted change is to a different function than what's under test. Can you clarify/expand the question to provide more information? Commented Feb 14, 2020 at 18:36
  • That error does not come from the code you've pasted, so it's impossible to debug. Commented Feb 15, 2020 at 11:43
  • Further, in response to your title, there's never any reason to mock an HTTP handler in Go. On the other hand, it's also unclear if that's actually what you're trying to do, since your question is incomplete. Commented Feb 15, 2020 at 11:43

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.