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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器