dongmi6102 2016-05-10 16:15
浏览 25
已采纳

如何使用大猩猩上下文对中间件软件包进行单元测试

I have this net/http server setup with several middleware in a chain and I can't find examples on how I should test these...

I am using basic net/http with the gorilla/mux router and one Handle looks somewhat like this:

r.Handle("/documents", addCors(checkAPIKey(getDocuments(sendJSON)))).Methods("GET")

In these I aggregate some data and supply them via Gorilla Context context.Set methods.

Usually I test my http functions with httptest, and I hope to do it with these as well but I can't figure out how and I am curious as to what is the best way. Should I test each middleware seperately? Should I prefill the appropriate context values then when they are needed? Can I test this entire chain at once so I can just check desired states on input?

  • 写回答

1条回答 默认 最新

  • doujie9252 2016-05-11 00:02
    关注

    I would not test anything involving Gorilla or any other 3rd party package. If you want to test to make sure it works, i'd setup some external test runner or integration suite for the endpoints of a running version of your app (e.g. a C.I. server).

    Instead, test your Middleware and Handlers individually - as those you have control over.

    But, if you are set on testing the stack (mux -> handler -> handler -> handler -> MyHandler), this is where defining the middleware globally using functions as vars could help:

    var addCors = func(h http.Handler) http.Handler {
      ...
    }
    
    var checkAPIKey = func(h http.Handler) http.Handler {
      ...
    }
    

    During normal use, their implementation remains the same with change.

    r.Handle("/documents", addCors(checkAPIKey(getDocuments(sendJSON)))).Methods("GET")
    

    But for unit testing, you can override them:

    // important to keep the same package name for
    // your test file, so you can get to the private
    // vars.
    package main
    
    import (
      "testing"
    )
    
    func TestXYZHandler(t *testing.T) {
    
      // save the state, so you can restore at the end
      addCorsBefore := addCors
      checkAPIKeyBefore := checkAPIKey
    
      // override with whatever customization you want
      addCors = func(h http.Handler) http.Handler {
        return h
      }
      checkAPIKey = func(h http.Handler) http.Handler {
        return h
      }
    
      // arrange, test, assert, etc.
      //
    
      // when done, be a good dev and restore the global state
      addCors = addCorsBefore
      checkAPIKey = checkAPIKeyBefore
    }
    

    If you find yourself copy-n-pasting this boiler plate code often, move it to a global pattern within your unit tests:

    package main
    
    import (
      "testing"
    )
    
    var (
      addCorsBefore = addCors
      checkAPIKeyBefore = checkAPIKey
    )
    
    func clearMiddleware() {
      addCors = func(h http.Handler) http.Handler {
        return h
      }
      checkAPIKey = func(h http.Handler) http.Handler {
        return h
      }
    }
    
    func restoreMiddleware() {
      addCors = addCorsBefore
      checkAPIKey = checkAPIKeyBefore
    }
    
    func TestXYZHandler(t *testing.T) {
    
      clearMiddleware()
    
      // arrange, test, assert, etc.
      //
    
      restoreMiddleware()
    }
    

    A side note on unit testing end points...

    Since middleware should operate with sensible defaults (expected to pass normally and not mutex state of the underlying stream of data you want to test in func), I advise to unit test the middleware outside of the context of your actual main Handler function.

    That way, you have one set of unit tests strictly for your middleware. And another set of tests focusing purely on the primary Handler of the url you are calling. It makes discovering the code much easier for newcomers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序