登录
首页 >  Golang >  Go问答

用Go Swagger生成的代码编写单元测试

来源:stackoverflow

时间:2024-03-24 22:42:38 261浏览 收藏

在使用 Go Swagger 生成的代码编写单元测试时,会出现两个常见问题。首先,无法使用常规 HTTP 测试来测试生成的代码,需要使用 HandlerFor 方法获取有效的 HTTP 处理程序。其次,服务器运行在不同的端口,无法硬编码永久端口号。解决方法是使用 HandlerFor 方法,并参考 Go Swagger 提供的示例代码,以获取有效的 HTTP 处理程序。

问题内容

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


正确答案


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

以上就是《用Go Swagger生成的代码编写单元测试》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>