0

I wanna start my app in BeforeSuit and run a GET Request. Is that possible?

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"))
        })
    })
})

At the moment it seems to start the server and not continue with the test. If I remove the BeforeSuite and instead start the server and run the test it seems fine.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Jen
  • 121
  • 1
  • 1
  • 7

1 Answers1

0

I'd imagine that app.Run blocks, since http.ListenAndServe does, in which case you probably need to do:

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

Generally, though, you wouldn't actual be listening on a port for your unit tests, you'd instead do something like this:

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"))
    })
})
dave
  • 62,300
  • 5
  • 72
  • 93
  • Hey ! yes that seemed to do the trick. Now I get golang.org/x/sys/unix.ECONNREFUSED (61) when I run the request with res, err := client.Do(req). any ideas? – Jen Jan 09 '20 at 06:56
  • See edit - basically with unit testing I've never seen it done where you actually are listening on a port, you'd instead use `httptest.NewRecorder` and pass in the request and response recorder to the handler directly. If you really want to listen for actual http requests, you'd probably need to use the `httptest.NewServer` somehow – dave Jan 09 '20 at 07:10
  • This is for integration test though so I would like to actually run the application & endpoints – Jen Jan 09 '20 at 13:14
  • go func() sends app to run in background and go func() itself does not block. So very possible that the server is not ready yet when test request is sent. – greedy52 Jan 09 '20 at 15:37