我想进行单元测试。为了简单起见,我只想确保调用“ JWTCheck”。我该怎么办?
这是我实现JWTCheck的文件:
type JWTChecker struct {
SubjectPrefix string
}
func (j *JWTChecker) JWTCheck(next http.Handler) http.Handler {
// Do something
}
这是我实现路由器的地方:
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
}
答案 0 :(得分:1)
您必须使用net/http/httptest
编写单元测试用例,测试用例的功能名称将Test
作为要测试的功能名称的前缀。文件名也将以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)
}
}
答案 1 :(得分:0)
按照@saddam建议编写您的测试代码。
然后使用go test
中的覆盖率支持来运行测试并验证JWTCheck
是否被覆盖。
go test -coverprofile=.coverage.out && go tool cover -html=.coverage.out