Golang: Testing HTTP requests

Unit testing HTTP calls to external services is pretty easy in Go. Let’s say we have some code that makes HTTP requests like so:

package something

import (
    "net/http"
)

func SomeFunc(url) string {
    rs, _ := http.Get(url)
    defer rs.Body.Close()
    body, _ := ioutil.ReadAll(rs)

    return string(body)   
}

We can test if the request is made and we get the response we want by mocking the external service. Below is the code:

package something

import (
    "net/http/httptest"
)

/**
This code uses Ginkgo and Gomega for unit tests but this can be easily adopted to any other framework or vanilla Go tests
**/
var _ = Describe("It makes HTTP requests", func () {
    Context("In some context", func () {
        It("makes an HTTP response which returns something", func() {
            server := httptest.NewServer(http.HandlerFunc(func(rs http.ResponseWriter, rq *http.Request) {
                if rq.RequestURI == `/` {
                    content := "Hello"
                    if err != nil {
                        fmt.Println("FL", err)
                    }
                    rs.Write(content)
                }
            }))
            defer server.Close()

            // If we were testing for the response, we do assert it.  
            Expect(someFunc(server.URL)).To(Equal("Hello")
        }
    })
})

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *