Gracias, Wikipedia.
TreeWeb::Artículos::Golang::How to test an http server in Golang
Permalink: http://www.treeweb.es/u/1311/ 30/01/2016

How to test an http server in Golang

First of all, an HTTP server could be anything implementing the `Handler` interface:
    0 
    1 type Handler interface {
    2     ServeHTTP(ResponseWriter, *Request)
    3 }
    4 

    5 
And you can start listening as simple as:
    0 
    1 http.ListenAndServe("0.0.0.0:8000", my_server)
    2 

    3 
But how about the testing? Easy, you should start a test server:
    0 
    1 ts := httptest.NewServer(my_server)

    2 
I have my test server. And now what? Call it like if it was any other http server:
    0 
    1 req, _ := http.Get(WHAT_IS_THE_URL)
    2 res, _ := http.DefaultClient.Do(req)
    3 

    4 
And now the difference: our test server has started a real server, the url is: ts.URL
Remember to close it after your tests are finished:
    0 
    1 ts.Close()

    2 
All this things put together:
    0 
    1 func Test_404_OK(t *testing.T) {
    2 
    3     server := NewServer()
    4 
    5     ts := httptest.NewServer(server)
    6     defer ts.Close()
    7 
    8     req, _ := http.NewRequest("GET", ts.URL+"/hello", strings.NewReader(""))
    9     res, _ := http.DefaultClient.Do(req)
   10 
   11     if 200 != res.StatusCode {
   12         t.Error("Expecting status code is 200")
   13     }
   14 }

   15 
Powered by TreeWeb
© TreeWeb 2010. Todos los derechos reservados