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 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!