【问题标题】:How to implement unit test with a code generated by go swagger如何使用 go swagger 生成的代码实现单元测试
【发布时间】:2021-09-30 13:08:08
【问题描述】:

我对这个 go swagger 生成的代码有两个问题,首先我用 go swagger 制作了我的第一个 api,但我的雇主要求我实现该单元(go test)但尝试执行通常的 http 测试不起作用, 下面是我的测试代码

// handlers_test.go
package handlers

import (
    "net/http"
    "net/http/httptest"
    "testing"
    "StocksApp/restapi/operations"
)

func TestStockHandler(t *testing.T) {
    // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
    // pass 'nil' as the third parameter.
    req, err := http.NewRequest("GET", "/api/v1/stocks", nil)
    if err != nil {
        t.Fatal(err)
    }

    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(operations.StocksHandler)

    // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
    // directly and pass in our Request and ResponseRecorder.
    handler.ServeHTTP(rr, req)

    // Check the status code is what we expect.
    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    expected := `{"alive": true}`
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

但我收到此错误,我不知道如何解决它

# StocksApp/handlers [StocksApp/handlers.test]
.\handlers_test.go:21:32: type operations.StocksHandler is not an expression
FAIL    StocksApp/handlers [build failed]

其次,当我运行 go run main.go 命令时,服务器运行在不同的端口,我想知道如何硬编码一个服务器将始终运行的永久端口号

【问题讨论】:

  • 如果没有您的实际处理程序文件,很难生成修复程序。在您的测试文件中operations.StocksHandler 是问题所在。这不是一个表达式(如错误所示)。这是您需要设置或模拟的依赖项吗?
  • stockHandler 不是一个方法吗?不确定,但可能是您必须调用该函数的情况。

标签: go go-testing go-swagger


【解决方案1】:

您可以使用HandlerFor 方法为您的操作获取有效的http.Handler。 请参阅以下示例:https://github.com/go-swagger/go-swagger/blob/master/examples/generated/restapi/operations/petstore_api.go#L436

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多