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

Kyo*_*yoo 2 unit-testing http mocking httphandler go

当我想从模拟中获取响应主体时,我遇到了问题,目前我已经创建了一些像这样的模拟:

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)
}
Run Code Online (Sandbox Code Playgroud)

然后我像这样创建 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)
}
Run Code Online (Sandbox Code Playgroud)

我得到的是一些错误(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) {  .....
Run Code Online (Sandbox Code Playgroud)

Kar*_*vya 6

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

go 中的 http 包附带了 httptest 来测试所有外部 http 调用依赖项。

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

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

基本上,这意味着使用接口并拥有自己的结构和存根函数调用,这将返回您想要的响应。

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

希望这可以帮助。