Testing http.Redirect() with httptest.NewServer

I have a redirect handler that I’m having trouble testing.
Bottom line; how do I test that http.Redirect() has been called and the location is what was expected?


Here is example code of what I have that demonstrates the issue:


package main

import "net/http"

func main() {
    server := &http.Server{Addr: ":8080"}
    http.HandleFunc("/", http.HandlerFunc(RedirectHandler))

func RedirectHandler(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "https://google.com", http.StatusFound)

and httpd_test.go

package main

import (

func TestRedirectHandler(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(RedirectHandler))

    response, err := http.Get(server.URL + "/")
    if err != nil {
        t.Errorf("Error in GET: %s\n", err.Error())
    if response.StatusCode != http.StatusFound {
        t.Errorf("Redirect failed, expected %d got %d\n", http.StatusFound, response.StatusCode)


Here is the test output and the output from running the server and sending a GET request:

➜  http_redirect_testing ls
httpd.go      httpd_test.go
➜  http_redirect_testing go test ./...
--- FAIL: TestRedirectHandler (0.54s)
	httpd_test.go:17: Redirect failed, expected 302 got 200
FAIL	github.com/dbyington/http_redirect_testing	0.556s
➜  http_redirect_testing go run httpd.go &
[2] 31115
➜  http_redirect_testing
[2]  + 31115 done       go run httpd.go
➜  http_redirect_testing curl -i localhost:8080
HTTP/1.1 302 Found
Location: https://google.com
Date: Sun, 14 Jan 2018 19:36:42 GMT
Content-Length: 41
Content-Type: text/html; charset=utf-8

<a href="https://google.com">Found</a>.

➜  http_redirect_testing

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.