How do I write integration tests for net / http code?

Here's some sample code:

package main

import (
    "net/http"
)

func Home(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, world!"))
}

func Router() *http.ServeMux {
    mux := http.NewServeMux()
    mux.HandleFunc("/", Home)
    return mux
}

func main() {
    mux := Router()
    http.ListenAndServe(":8080", mux)
}

      

This is the test script I wrote:

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestMain(t *testing.T) {
    w := httptest.NewRecorder()
    r, _ := http.NewRequest("GET", "/", nil)
    Router().ServeHTTP(w, r)
    if w.Body.String() != "Hello, world!" {
        t.Error("Wrong content:", w.Body.String())
    }
}

      

Does this test actually send an HTTP request over a TCP socket and reach the endpoint /

? Or is it just a function call with no HTTP connection?

Update

Based on the answer given by @ffk, I wrote the test like this:

func TestMain(t *testing.T) {
    ts := httptest.NewServer(Router())
    defer ts.Close()
    req, _ := http.NewRequest("GET", ts.URL+"/", nil)
    client := http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    if string(body) != "Hello, world!" {
        t.Error("Wrong content:", string(body))
    }
}

      

+3


source to share


1 answer


If you want to instantiate a test server accessible via a random tcp port at 127.0.0.1 use the following:

httpHandler := getHttpHandler() // of type http.Handler
testServer := httptest.NewServer(httpHandler)
defer testServer.Close()
request, err := http.NewRequest("GET", testServer.URL+"/my/url", nil)
client := http.Client{}
response, err := client.Do(request)

      



For more information see https://golang.org/pkg/net/http/httptest/#NewServer

+1


source







All Articles