登录
首页 >  Golang >  Go问答

推送功能在 golang 中的测试与使用

来源:stackoverflow

时间:2024-02-24 16:57:29 225浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《推送功能在 golang 中的测试与使用》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试为 http.pusher 编写单元测试。我尝试使用 httptest.newrecorder() 作为 http.responsewriter 但类型转换失败。我还能如何编写测试?

//My function 
    func push(w http.ResponseWriter, resource string) error {
        pusher, ok := w.(http.Pusher)
        if ok {
            return pusher.Push(resource, nil)
        }
        return fmt.Errorf("Pusher not supported")
    }

    //My test 
    func TestPush(t *testing.T) {
        resource := "static/css/main.css"
        response := httptest.NewRecorder()
        got := push(response, resource)

        if got != nil {
            t.Errorf("Error : %v", got)
        }
    }

输出是“pusher not support”,我认为 w.(http.pusher) 失败了。


解决方案


您可以创建一个也实现 http.Pusher 的模拟 http.ResponseWriter,并在测试期间通过它。

这是一个适合您的可测试函数的简单实现:

type pusher struct {
    http.responsewriter
    err    error // err to return from push()
    target string
    opts   *http.pushoptions
}

func (p *pusher) push(target string, opts *http.pushoptions) error {
    // record passed arguments for later inspection
    p.target = target
    p.opts = opts
    return p.err
}

测试函数示例:

func testpush(t *testing.t) {
    resource := "static/css/main.css"
    p := &pusher{}
    err := push(p, resource)

    if err != p.err {
        t.errorf("expected: %v, got: %v", p.err, err)
    }
    if resource != p.target {
        t.errorf("expected: %v, got: %v", p.target, resource)
    }
}

请注意,这个简单的 pusher 嵌入了 http.responsewriter 类型,这将使​​其本身成为 http.responsewriter (它将使 pusher 实现 http.responsewriter)。在测试过程中,我们保留了此字段 nil,因为可测试的 push() 函数没有使用其中的任何内容。如果您的真实函数会调用它的方法,例如 responsewriter.header(),这当然会导致运行时恐慌。在这种情况下,您还必须提供有效的 http.responsewriter,例如:

p := &pusher{ResponseWriter: httptest.NewRecorder()}

好了,本文到此结束,带大家了解了《推送功能在 golang 中的测试与使用》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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