0

我对这个 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 命令时,服务器运行在不同的端口,我想知道如何硬编码服务器将始终运行的永久端口号

4

1 回答 1

0

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

于 2022-01-14T15:27:53.297 回答