如何使用func(w http.ResponseWriter,r * http.Request)模拟测试`

问题描述 投票:-2回答:1

当我想从我的嘲讽中获得回应时,我遇到了问题,目前,我已经创建了这样的模拟游戏:

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)
}

然后我像这样创建handler_test.go:

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)
}

我得到了一些错误((http.HandlerFunc)(0x165e020)(不能将func类型用作参数)

我不知道如何解决。由于我正在使用这样的处理程序:

func (ah *CampaignHandler) GetCampaigns(store store.Store) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {  .....
unit-testing http go mocking httphandler
1个回答
0
投票

如果您正在对外部服务进行HTTP调用并希望对其进行测试并获得模拟响应,则可以使用httptest

http包中附带的httptest可以测试您所有的外部http调用依赖项。

请在此处找到示例:https://golang.org/src/net/http/httptest/example_test.go

如果这不是您的用例,则最好使用存根,并且可以在此处找到实现的方法:https://dev.to/jonfriesen/mocking-dependencies-in-go-1h4d

基本上,这是使用接口并拥有自己的结构和存根函数调用,它们将返回所需的响应。

如果要在测试中添加一些语法糖,则可以使用testify:https://github.com/stretchr/testify

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.