0

我想在 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 并启动服务器并运行测试,它似乎很好。

4

1 回答 1

0

我想这会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"))
    })
})
于 2020-01-09T00:35:34.290 回答