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?
Thanks!
Here is example code of what I have that demonstrates the issue:
httpd.go
package main
import "net/http"
func main() {
server := &http.Server{Addr: ":8080"}
http.HandleFunc("/", http.HandlerFunc(RedirectHandler))
server.ListenAndServe()
}
func RedirectHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://google.com", http.StatusFound)
}
and httpd_test.go
package main
import (
"testing"
"net/http/httptest"
"net/http"
)
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
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