如何测试以确保函数被调用?

时间:2018-07-06 17:47:06

标签: unit-testing go gorilla

我想进行单元测试。为了简单起见,我只想确保调用“ 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
}

2 个答案:

答案 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