mardi 19 mai 2015

How to write integration tests for net/http based code?

Here is an example 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 integration tests 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())
    }
}

Is this code really sending an HTTP request through a TCP socket and reaching the end point /? Or this is just calling the function without making an HTTP connection?

Aucun commentaire:

Enregistrer un commentaire