登录
首页 >  Golang >  Go问答

在 Go 中对路由器提供程序进行单元测试

来源:stackoverflow

时间:2024-04-06 09:36:32 416浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《在 Go 中对路由器提供程序进行单元测试》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我的项目中有一个文件:

package handlers

import (
    "github.com/gorilla/mux"
)

type ihandlerprovider interface {
    getrouter() *mux.router
}

type handlerprovider struct{}

func (h handlerprovider) getrouter() *mux.router {
    r := mux.newrouter()
    r.handlefunc("/health", health).methods("get")
    return r
}

进行单元测试的正确方法是什么?例如:

package handlers

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGetRouterOk(t *testing.T) {
    var subject IHandlerProvider = HandlerProvider{}
    router := subject.GetRouter()
    assert.NotNil(t, router)
}

我可以断言对象不为空,但如何测试路由是否正确?


解决方案


如果您想测试路由器是否返回预期的处理程序(与测试行为),您可以执行如下操作:

r := mux.newrouter()
r.handlefunc("/a", handlera).methods("get")
r.handlefunc("/b", handlerb).methods("get")

req, err := httptest.newrequest("get", "http://example.com/a", nil)
require.noerror(err, "create request")

m := &mux.routematch{}
require.true(r.match(req, m), "no match")

v1 := reflect.valueof(m.handler)
v2 := reflect.valueof(handlera)
require.equal(v1.pointer(), v2.pointer(), "wrong handler")

您可以使用httptest包。

handlers.go

package handlers

import (
    "net/http"
    "github.com/gorilla/mux"
)

type ihandlerprovider interface {
    getrouter() *mux.router
}

type handlerprovider struct {}

func health(w http.responsewriter, r *http.request) {
    w.write([]byte("ok"))
}

func (h handlerprovider) getrouter() *mux.router {
    r := mux.newrouter()
    r.handlefunc("/health", health).methods("get")
    return r
}

handlers_test.go

package handlers

import (
  "testing"
  "bytes"
  "io/ioutil"
  "net/http/httptest"
)


func testgetrouterok(t *testing.t) {
  assertresponsebody := func(t *testing.t, s *httptest.server, expectedbody string) {
        resp, err := s.client().get(s.url+"/health")
        if err != nil {
            t.fatalf("unexpected error getting from server: %v", err)
        }
        if resp.statuscode != 200 {
            t.fatalf("expected a status code of 200, got %v", resp.statuscode)
        }
        body, err := ioutil.readall(resp.body)
        if err != nil {
            t.fatalf("unexpected error reading body: %v", err)
        }
        if !bytes.equal(body, []byte(expectedbody)) {
            t.fatalf("response should be ok, was: %q", string(body))
        }
  }
  
  var subject ihandlerprovider = handlerprovider{}
  router := subject.getrouter()
  s := httptest.newserver(router)
  defer s.close()
  assertresponsebody(t, s, "ok")
}

单元测试结果:

=== RUN   TestGetRouterOk
--- PASS: TestGetRouterOk (0.00s)
PASS
ok      github.com/mrdulin/golang/src/stackoverflow/64584472    0.097s

覆盖范围:

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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