Fake or Mock client/server implementations for testing

111 views
Skip to first unread message

Amjad Masad

unread,
Jan 28, 2015, 2:19:59 PM1/28/15
to goril...@googlegroups.com
I looked in the repo and didn't find anything. What's the best way to test my server package without resorting to exposing internal methods?

Mahmud Ridwan

unread,
Jan 28, 2015, 3:15:46 PM1/28/15
to goril...@googlegroups.com
You could do something like this perhaps (assuming I understood the question):
 
~~~
package main
 
import (
        "io"
        "net/http"
        "net/http/httptest"
        "os"
 
)
 
func main() {
        r := mux.NewRouter()
        r.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
                w.Write([]byte("Hello, world\n"))
        })
 
        ts := httptest.NewServer(r)
        res, err := http.Get(ts.URL + "/hello")
        catch(err)
 
        io.Copy(os.Stdout, res.Body)
}
 
func catch(err error) {
        if err != nil {
                panic(err)
        }
}
~~~
 
So, the "net/http/httptest" package provides some pretty neat ways to test your HTTP server. You can know more about it here: http://golang.org/pkg/net/http/httptest/
 
In the example above, I declared a Gorilla router, added a handler function. Then I created a test server using the router and made the http package perform a GET request on that "/hello" URL. Finally I copied the response body to the standard output. But this is where you can get creative; once you set up the test server, you can hit any endpoint and then validate the responses as desired.
 
Hope this helps.
 
Best regards,
Ridwan
 
 
 
On Thu, Jan 29, 2015, at 01:19 AM, Amjad Masad wrote:
I looked in the repo and didn't find anything. What's the best way to test my server package without resorting to exposing internal methods?


--
You received this message because you are subscribed to the Google Groups "Gorilla web toolkit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gorilla-web...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
 
Reply all
Reply to author
Forward
0 new messages