dongxi1680 2018-10-11 21:46
浏览 53
已采纳

Golang单元测试HTTP处理程序

I want to make a simple server that can receive web hook requests from services and deal with them for me. And for fun I wanted to build that in Go, since that sounds like a nice language and this is a simple project to start with.

The server seems to be working fine, but I can't get my unittest to work. On inspection it seems that every url gives a 404. What am I doing wrong?

main.go

package main

import (
    "fmt"
    "log"
    "net/http"
)

func pingHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "{\"check\": \"online\"}")
}

func main() {
    // Start server
    log.Print("Starting server")
    http.HandleFunc("/ping", pingHandler)
    log.Fatal(http.ListenAndServe(":7080", nil))
}

main_test.go

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestPingHandler(t *testing.T) {
    req, err := http.NewRequest("GET", "/ping", nil)
    if err != nil {
        t.Fatal(err)
    }
    rr := httptest.NewRecorder()
    http.DefaultServeMux.ServeHTTP(rr, req)

    status := rr.Code
    fmt.Println(status)
}
  • 写回答

1条回答 默认 最新

  • dtja73027 2018-10-11 21:49
    关注

    Your handler is registered in main, but main is not invoked when you're running unit tests. So, when you try to test via DefaultMux, no handlers are registered, and you get a 404. However, generally you test the handler, not the mux; so instead of this line:

    http.DefaultServeMux.ServeHTTP(rr, req)
    

    You would instead test:

    pingHandler(rr, req)
    

    Which will work even though main is not executed to register the handler, because you're now testing the handler directly.

    You should also use httptest.NewRequest to create requests for testing; http.NewRequest is for creating requests for use in a Client.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码