gpt4 book ai didi

go - 如何测试一个端点?

转载 作者:IT王子 更新时间:2023-10-29 02:03:03 25 4
gpt4 key购买 nike

我用go写了一个小测试函数。我很难向实际端点发出请求并对其进行测试。我尝试导入具有处理函数的文件(我想我正在尝试导入整个目录:import ("."))。我的 project.go 和 handler_test.go 都在同一个目录中(我认为这不重要)。有人可以提醒我,以便我可以编写更多测试。这是我的 project.go:

package main

import (
"encoding/json"
"net/http"

"github.com/gorilla/mux"
"github.com/rs/cors"

)

type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Address *Address `json:"address,omitempty"`
}

type Address struct {
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
}

var people []Person;

func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for _, item := range people {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Person{})
}


func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
json.NewEncoder(w).Encode(people)
}

func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
var person Person
_ = json.NewDecoder(req.Body).Decode(&person)
person.ID = params["id"]
people = append(people, person)
json.NewEncoder(w).Encode(people)
}

func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(people)
}

func main() {
Router := mux.NewRouter()
people = append(people, Person{ID: "1", Firstname: "sarath", Lastname: "v", Address: &Address{City: "sunnyvale", State: "CA"}})
people = append(people, Person{ID: "2", Firstname: "dead", Lastname: "pool"})

// router.PathPrefix("/tmpfiles/").Handler(http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("."))))

Router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
Router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
Router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST")

c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowCredentials: true,
})

// Insert the middleware
handler := c.Handler(Router)
http.ListenAndServe(":12345", handler)

}

这是我的 handler_test.go。在此代码中,我正在测试 GetPersonEndPoint。

package main

import (
"."
"net/http"
"net/http/httptest"
"testing"
"encoding/json"
)

func checkResponseCode(t *testing.T, expected, actual int) {
if expected != actual {
t.Errorf("Expected response code %d. Got %d\n", expected, actual)
}
}

func executeRequest(req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(GetPersonEndpoint)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
fmt.Printf("Handler returned wrong status code: got %v want %v" , status, http.statusOk);
}
return rr
}

func TestGetPersonEndPoint(t *testing.T){
req, _ := http.NewRequest("GET", "/people/5", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusNotFound, response.Code)
var m map[string]string
json.Unmarshal(response.Body.Bytes(), &m)
if m["error"] != "Product not found" {
t.Errorf("Expected the 'error' key of the response to be set to 'Product not found'. Got '%s'", m["error"])
}
}

最后这是错误:

./new.go:14: main redeclared in this block
previous declaration at ./myproject.go:62
./new.go:20: not enough arguments in call to server.ListenAndServeTLS
have ()
want (string, string)

最佳答案

看看我写的一些 http 测试:https://github.com/eamonnmcevoy/go_web_server/blob/master/pkg/server/user_router_test.go

    // Arrange
us := mock.UserService{}
testUserRouter := NewUserRouter(&us, mux.NewRouter())
...
w := httptest.NewRecorder()
r, _ := http.NewRequest("PUT", "/", payload)
r.Header.Set("Content-Type", "application/json")
testUserRouter.ServeHTTP(w, r)

只需创建一个路由器实例并使用 go 的 httptest 调用端点。此代码段将在默认端点 /

执行 PUT 请求

关于go - 如何测试一个端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com