I want to do unit test. Just to make it simple, I just want to make sure that the "JWTCheck" get called. How do I do that?
This is the file where I implement the JWTCheck:
type JWTChecker struct {
SubjectPrefix string
}
func (j *JWTChecker) JWTCheck(next http.Handler) http.Handler {
// Do something
}
And this is where I implement the router:
import (
"net/http"
"github.com/gorilla/mux"
)
// Router returns a preconfigured router for application
func (a *Adapter) Router() http.Handler {
router := mux.NewRouter()
jwtChecker := JWTChecker{
SubjectPrefix: "myappName",
}
/* Setup Loans Routes */
loanrouter := router.PathPrefix("/lending/loans").Subrouter()
if !a.Debug {
loanrouter.Use(jwtChecker.JWTCheck)
}
loanrouter.HandleFunc("/customer/{customerid}/loan/{loanid}", a.GetLoan).Methods("GET")
return router
}
You have to use net/http/httptest
to write unit test case and the function name of the test cases would Test
as prefix to the function name you wants to test. Also the filename will start with yourfilename_test.go
func Test<YourFuncName>(t *testing.T) {
req, err := http.NewRequest("GET", "<your function url>", nil)
if err != nil {
panic(err.Error())
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Request failed, got: %d, expected: %d.", w.Code, http.StatusOK)
}
}
Follow @saddam advice to write your test code.
Then use coverage support in go test
to run the test and verify that JWTCheck
is covered.
go test -coverprofile=.coverage.out && go tool cover -html=.coverage.out