用Golang测试一个简单的端点(最常见方法)

83 阅读1分钟

在Golang中,有几种测试端点的方法,但我在此向你展示最常见的方法。

代码

package main

import (
	"log"
	"net/http"
)

func main() {
	handler := http.NewServeMux()
	handler.HandleFunc("/api/v1/users", users)
	
	log.Fatal(http.ListenAndServe(":8080", handler))
}

func users(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("inanzzz"))
}

例子

package main

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

func Test_users(t *testing.T)  {
	req, err := http.NewRequest(http.MethodGet, "/api/v1/users", nil)
	if err != nil {
		t.Fatal(err)
	}

	res := httptest.NewRecorder()
	handler := http.HandlerFunc(users)

	handler.ServeHTTP(res, req)

	if http.StatusOK != res.Code  {
		t.Error("expected", http.StatusOK, "got", res.Code)
	}
	if "inanzzz" != res.Body.String() {
		t.Error("expected inanzzz got", res.Body.String())
	}
}
package main

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

func Test_users(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
	res := httptest.NewRecorder()

	users(res, req)

	// Instead of lines below, you can just use res.Code and res.Body.String() directly.

	result := res.Result()

	body, err := ioutil.ReadAll(result.Body)
	if err != nil {
		t.Fatal(err)
	}
	result.Body.Close()

	if http.StatusOK != result.StatusCode  {
		t.Error("expected", http.StatusOK, "got", result.StatusCode)
	}
	if "inanzzz" != string(body) {
		t.Error("expected inanzzz got", string(body))
	}
}