HTTP Handler Testing in Go Language

hunterlong September 16, 2016 0

This is a short snippet for your Go Language tests that need the response of a http server handler while POST-ing form value to handler. The function will check if body of response includes the string of your choice.

Hander

1
2
3
func ShowIndexHandler(w http.ResponseWriter, r *http.Request) {
 
}

}

HTTP Test Function

This function will give you everything you need to get a response from your HTTP handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
// import "net/http/httptest"
 
func DoHTTPTest(handlerName http.HandlerFunc, method string, array map[string]string, expected string) bool {
	req, err := http.NewRequest(method, "/blank", nil)
 
	q := req.URL.Query()
 
	for k, v := range array{
		q.Add(k, v)
	}
 
	req.URL.RawQuery = q.Encode()
 
	if err != nil {
		panic(err)
	}
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(handlerName)
 
	handler.ServeHTTP(rr, req)
 
	fmt.Println("Response: ", rr.Body.String())
 
	if strings.Contains(rr.Body.String(),expected) {
		return true
	} else {
		return false
	}
 
}

func DoHTTPTest(handlerName http.HandlerFunc, method string, array map[string]string, expected string) bool {
req, err := http.NewRequest(method, "/blank", nil)

q := req.URL.Query()

for k, v := range array{
q.Add(k, v)
}

req.URL.RawQuery = q.Encode()

if err != nil {
panic(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(handlerName)

handler.ServeHTTP(rr, req)

fmt.Println("Response: ", rr.Body.String())

if strings.Contains(rr.Body.String(),expected) {
return true
} else {
return false
}

}

Actual Test Function

This function would go inside your test for your go language application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func TestHandlerTest(t *testing.T) {
 
    // insert your form values here
    output := map[string]string{
		"email": "[email protected]",
		"password": "password123",
    }
 
    // what do you expect the response to include? (if "success" is in any part of response)
    expects := "success"
 
    // get true/false if string was included in response
    testResponse := DoHTTPTest(ShowIndexHandler, "POST", output, expects)
 
    // fail if response didn't include "success"
    if !testResponse {
       t.Fail()
    }
}

// insert your form values here
output := map[string]string{
"email": "[email protected]",
"password": "password123",
}

// what do you expect the response to include? (if "success" is in any part of response)
expects := "success"

// get true/false if string was included in response
testResponse := DoHTTPTest(ShowIndexHandler, "POST", output, expects)

// fail if response didn’t include "success"
if !testResponse {
t.Fail()
}
}

Leave A Response »