gpt4 book ai didi

go - 在端点上运行测试之前,无法在BeforeSuit中启动应用程序服务器

转载 作者:行者123 更新时间:2023-12-01 22:26:36 24 4
gpt4 key购买 nike

我想在BeforeSuit中启动我的应用程序并运行GET请求。那可能吗?

example_suite_test.go

func TestExample(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Example Suite")
}

example_test.go
var appTest *app.Application

var _ = BeforeSuite(func() {
app = &app.Application{}
app.Run(":8080") // runs http.ListenAndServe on given address
})

var _ = Describe("Example", func() {

Context("When calling '/example' endpoint...", func() {

req, err := http.NewRequest("GET", "http://localhost:8080/example", nil)
client := http.DefaultClient
res, err := client.Do(req)
It("Should get response 200 OK", func() {
Expect(res.Status).To(Equal("200 OK"))
})
})
})


目前,它似乎正在启动服务器,而不是继续测试。如果我删除BeforeSuite而是启动服务器并运行测试,那似乎很好。

最佳答案

我想象app.Run会阻塞,因为http.ListenAndServe会阻塞,在这种情况下,您可能需要这样做:

var _ = BeforeSuite(func() {
app = &app.Application{}
go func() {
app.Run(":8080") // runs http.ListenAndServe on given address
}()
})

通常,尽管如此,您实际上并不会在端口上监听单元测试,而应该这样做:
var _ = Describe("Example", func() {
Context("When calling '/example' endpoint...", func() {

req, err := http.NewRequest("GET", "http://localhost:8080/example", nil)
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.ExampleHandler)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
It("Should get response 200 OK", func() {
Expect(rr.Result().Status).To(Equal("200 OK"))
})
})

关于go - 在端点上运行测试之前,无法在BeforeSuit中启动应用程序服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59652161/

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