I would not test anything involving Gorilla or any other 3rd party package. If you want to test to make sure it works, i'd setup some external test runner or integration suite for the endpoints of a running version of your app (e.g. a C.I. server).
Instead, test your Middleware and Handlers individually - as those you have control over.
But, if you are set on testing the stack (mux -> handler -> handler -> handler -> MyHandler), this is where defining the middleware globally using functions as vars could help:
var addCors = func(h http.Handler) http.Handler {
...
}
var checkAPIKey = func(h http.Handler) http.Handler {
...
}
During normal use, their implementation remains the same with change.
r.Handle("/documents", addCors(checkAPIKey(getDocuments(sendJSON)))).Methods("GET")
But for unit testing, you can override them:
package main
import (
"testing"
)
func TestXYZHandler(t *testing.T) {
addCorsBefore := addCors
checkAPIKeyBefore := checkAPIKey
addCors = func(h http.Handler) http.Handler {
return h
}
checkAPIKey = func(h http.Handler) http.Handler {
return h
}
addCors = addCorsBefore
checkAPIKey = checkAPIKeyBefore
}
If you find yourself copy-n-pasting this boiler plate code often, move it to a global pattern within your unit tests:
package main
import (
"testing"
)
var (
addCorsBefore = addCors
checkAPIKeyBefore = checkAPIKey
)
func clearMiddleware() {
addCors = func(h http.Handler) http.Handler {
return h
}
checkAPIKey = func(h http.Handler) http.Handler {
return h
}
}
func restoreMiddleware() {
addCors = addCorsBefore
checkAPIKey = checkAPIKeyBefore
}
func TestXYZHandler(t *testing.T) {
clearMiddleware()
restoreMiddleware()
}
A side note on unit testing end points...
Since middleware should operate with sensible defaults (expected to pass normally and not mutex state of the underlying stream of data you want to test in func), I advise to unit test the middleware outside of the context of your actual main Handler function.
That way, you have one set of unit tests strictly for your middleware. And another set of tests focusing purely on the primary Handler of the url you are calling. It makes discovering the code much easier for newcomers.