简体   繁体   English

Golang单元测试HTTP处理程序

[英]Golang unittest http handler

I want to make a simple server that can receive web hook requests from services and deal with them for me. 我想做一个简单的服务器,可以接收来自服务的Web挂钩请求并为我处理它们。 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. 为了娱乐,我想在Go中构建它,因为这听起来像是一种不错的语言,而且这是一个简单的项目。

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? 经检查,似乎每个URL都给出404。我在做什么错?

main.go 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 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)
}

Your handler is registered in main , but main is not invoked when you're running unit tests. 您的处理程序已在main注册,但在运行单元测试时不会调用main 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; 因此,当您尝试通过DefaultMux进行测试时,未注册任何处理程序,但您得到404。但是,通常您测试的是处理程序,而不是多路复用器。 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. 即使未执行main来注册处理程序,该方法也将起作用,因为您现在正在直接测试处理程序。

You should also use httptest.NewRequest to create requests for testing; 您还应该使用httptest.NewRequest创建测试请求; http.NewRequest is for creating requests for use in a Client . http.NewRequest用于创建要在Client使用的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM