登录
首页 >  Golang >  Go问答

定义未使用的模拟方法

来源:stackoverflow

时间:2024-03-02 10:18:25 461浏览 收藏

一分耕耘,一分收获!既然都打开这篇《定义未使用的模拟方法》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在尝试测试以下方法:

//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)
}

在本例中,如果 r 包含需要授权的 url,并且授权成功,则会调用 sessionrelease

了解这一点可能很重要:

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,该实例只为 checktokenandsetsession 返回 nil(当然,会话设置被抽象出来,用于创建存根对象本身,它具有 session)和一个 middlewarestzqbendcz qb充满了getinfo() 的假 nonauthurls
  • 创建一个模拟 session.store,对于除健全性测试之外的所有测试,预计对 sessionrelease 的调用为零。

可能值得注意(但假设)我正在使用 testify、mockery 库来进行模拟和断言。

测试

这样实现:

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 不会返回任何内容,因此我什至没有使用 return()

我是否断言它应该被调用零次,对吗?


解决方案


我觉得这有点傻。

问题是我很烦恼

sessionmock.assertexpectations(t)

当我可以简单地说

sessionMock.AssertNotCalled(t, "SessionRelease", w)

(有关该方法的文档 here

执行后者解决了问题,并且完全达到了我想要完成的目标。

今天关于《定义未使用的模拟方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>