doufan3408 2019-06-20 07:41
浏览 384
已采纳

在golang中测试http.Pusher和push函数

I am trying to write a unit test for http.Pusher. I tried using httptest.NewRecorder() as http.ResponseWriter but the type conversion failed. How else can I write the test?

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

The output is "Pusher not supported", which I assume that w.(http.Pusher) failed.

  • 写回答

1条回答 默认 最新

  • dqkx69935 2019-06-20 08:06
    关注

    You may create a mocked http.ResponseWriter that also implements http.Pusher, and pass that during testing.

    Here's a simple implementation that suits your testable function:

    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
    }
    

    Example test function:

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

    Note that this simple pusher embeds the http.ResponseWriter type which will make it itself an http.ResponseWriter (it will make pusher implement http.ResponseWriter). During the test we left this field nil because the testable push() function did not use anything from it. If your real function would call methods of it such as ResponseWriter.Header(), that would cause a runtime panic of course. In that case you have to provide a valid http.ResponseWriter too, e.g.:

    p := &pusher{ResponseWriter: httptest.NewRecorder()}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路