我正在尝试测试以下方法:
//AuthenticationMiddleware Middleware which handles all of the authentication.
func AuthenticationMiddleware(context context.ContextIntf, w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
//Check if url is one that doesn't need authorization. If not than send them to the login page.
for _, url := range AuthMWInstance.GetInfo().nonAuthURLs {
if url.Method == r.Method && strings.Contains(r.URL.Path, url.DomainName) {
next(w, r)
return
}
}
if errSt := CheckForAuthorization(context, r, w); errSt != nil {
responses.Write(w, responses.Unauthorized(*errSt))
return
}
defer context.GetInfo().Session.SessionRelease(w)
next(w, r)
}
在这种情况下,如果SessionRelease
包含需要授权的URL,并且授权成功,则有一个r
被调用。
重要的是要知道:
type MiddlewareSt struct {
//NonAuthUrls URLs that can be accessed without a token.
nonAuthURLs []url.URLSt
}
type MiddlewareIntf interface {
GetInfo() *MiddlewareSt
CheckTokenAndSetSession(context context.ContextIntf, r *web.Request, w web.ResponseWriter,
token string, scope string, remoteAddr string) *errors.ErrorSt
}
var AuthMWInstance MiddlewareIntf
CheckForAuthorization
的返回值最终取决于AuthMWInstance
我的测试策略
AuthMWInstance
初始化为nil
的{{1}}(当然,会话设置被抽象为存根对象本身的创建) ,其中包含CheckTokenAndSetSession
)和Session
中充满MiddlewareSt
的伪造nonAuthURLs
session.Store
,对于除健全性测试之外的所有测试,期望对GetInfo()
的调用为零。 可能值得注意(但假设是)我正在使用testify,mockery库来进行模拟和声明。
测试
是这样实现的:
SessionRelease
运行时行为
func TestAuthenticationMiddleware(t *testing.T) {
// bring in the errors
sdkTesting.InitErrors()
// create/set up the test doubles
// mock session
sessionMock := new(testing_mock.MockStore)
// temporarily set AuthMWInstance to a stub
instance := AuthMWInstance
AuthMWInstance = &StubMiddlewareInstance{
Session: sessionMock,
}
// AuthMWInstance.Session
defer func() { AuthMWInstance = instance }()
// fake ResponseWriter
w := new(StubResponseWriter)
// fake web requests
requestWithoutAuth := new(web.Request)
requestWithoutAuth.Request = httptest.NewRequest("GET",
"http://example.com/logout",
nil,
)
// do tests here
t.Run("AuthorizationNotRequired", func(t *testing.T) {
// place expectations on sessionMock, namely that it does
// **not** invoke `SessionRelease`
sessionMock.On("SessionRelease", w).
Times(0)
AuthenticationMiddleware(new(context.Context),
w,
requestWithoutAuth,
web.NextMiddlewareFunc(func(web.ResponseWriter, *web.Request) {}))
sessionMock.AssertExpectations(t)
})
}
,我就像:
sessionMock.On("SessionRelease", w).
Times(0)
注意 sessionMock.On("SessionRelease", w).
Once()
不返回任何内容,因此,我什至不费心使用session.Store.SessionRelease
。
我是否断言它恰好被称为零次?
答案 0 :(得分:0)
对此我有点傻。
问题是我很烦
coalesce
我本来可以简单地说
sessionMock.AssertExpectations(t)
(有关该方法here的文档)
通过后者解决了该问题,并且完全按照我的意图完成了。