亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我應該如何使用 gorilla 上下文對中間件包進行單元測試

我應該如何使用 gorilla 上下文對中間件包進行單元測試

Go
函數式編程 2022-01-10 14:51:46
我有這個 net/http 服務器設置,鏈中有幾個中間件,我找不到關于如何測試這些的示例......我在 gorilla/mux 路由器上使用基本的 net/http,一個 Handle 看起來有點像這樣:r.Handle("/documents", addCors(checkAPIKey(getDocuments(sendJSON)))).Methods("GET")在這些中,我匯總了一些數據并通過 Gorilla Context context.Set 方法提供它們。通常我用httptest測試我的http函數,我也希望用這些來做,但我不知道怎么做,我很好奇什么是最好的方法。我應該單獨測試每個中間件嗎?我應該在需要時預先填充適當的上下文值嗎?我可以一次測試整個鏈,以便我可以檢查輸入的所需狀態嗎?
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

我不會測試任何涉及 Gorilla 或任何其他 3rd 方包的東西。如果您想測試以確保它正常工作,我會為您的應用程序運行版本(例如 CI 服務器)的端點設置一些外部測試運行程序或集成套件。


相反,單獨測試您的中間件和處理程序 - 就像您可以控制的那樣。


但是,如果您準備測試堆棧(mux -> 處理程序 -> 處理程序 -> 處理程序 -> MyHandler),那么使用函數作為變量全局定義中間件可能會有所幫助:


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

  ...

}


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

  ...

}

在正常使用期間,它們的實現保持不變。


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

但是對于單元測試,您可以覆蓋它們:


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

}

如果您發現自己經常復制粘貼此樣板代碼,請將其移至單元測試中的全局模式:


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

}

關于單元測試端點的旁注......


由于中間件應該以合理的默認值運行(預計正常傳遞,而不是您要在 func 中測試的底層數據流的互斥狀態),我建議在實際主 Handler 函數的上下文之外對中間件進行單元測試。


這樣,您就有了一組嚴格針對中間件的單元測試。另一組測試完全專注于您正在調用的 url 的主要處理程序。它使新手更容易發現代碼。


查看完整回答
反對 回復 2022-01-10
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號