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

标签 unit-testing http go mocking httphandler

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

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) {  .....

最佳答案

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

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

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

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

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

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

希望这有帮助。

关于unit-testing - 如何使用 ` func(w http.ResponseWriter, r *http.Request) `进行模拟测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60231601/

相关文章:

java - 合并来自多个 Jenkins 作业的测试覆盖率和测试结果

rest - 如果更改密码时旧密码不匹配,我应该使用什么状态码?

apache 服务器 - 如何将 http 重定向到 https

go - 具有接口(interface)类型和结构指针的 channel 作为具体类型

c# - 'System.ComponentModel.Win32Exception : The operation completed successfully' while debugging unit test

java - OkHttp MockWebServer 重启时接受连接失败

typescript - 你如何用 typescript Jest 在两次测试之间重置测试对象?

php - 从 javascript 和 PHP 上下文发布数据时使用相同的 PHP 类很困难

go - 获取结构字段类型的简单字符串表示

go - GKE 无法将卷装载到部署/Pod : timed out waiting for the condition