我正在使用 gin gonic 中的 getstream 的 Go 庫,并意識到我的端點將嚴重依賴stream_chat.Client.
例如,在/v1/chat/test-token下面的端點stream_chat.Client(然后我可以在撰寫單元測驗時模擬這些方法。stream_chat.ClientMockClientchatClient.UpsertUserchatClient.CreateToken
func main() {
config.Load()
server := gin.New()
chatClient, err := stream_chat.NewClient(config.StreamApiKey, config.StreamApiSecret)
if err != nil {
log.Err(err)
os.Exit(2)
}
v1 := server.Group("/v1")
{
v1.GET("/chat/test-token/", func(c *gin.Context) {
_, err := chatClient.UpsertUser(&stream.User{
ID: "test-user",
Role: "admin",
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
}
token, _ := chatClient.CreateToken("test-user", time.Time{})
c.JSON(http.StatusOK, gin.H{
"token": token,
})
})
}
server.Run(fmt.Sprintf(":%s", config.Port))
}
It seems to me to be quite laborious to document each method that I'd use from stream_chat.Client in order to keep a good test coverage on the endpoints, so I wonder what one should do in this case?
- Is maintaining an interface for
stream_chat.Clientthe correct way to go? - Less relevant: Is there a way to properly decouple the
gin.HandlerFunc, i.e.func(c *gin.Context)from the creation ofstream_chat.Client? - Even less relevant: Is it better to create a singleton
stream_chat.Clientor should I create a new client for each endpoint that requires a client?
uj5u.com熱心網友回復:
為 stream_chat.Client 維護一個介面是正確的方法嗎?
如果你有一個非介面依賴并且你希望用它對處理程式進行單元測驗,那么是的。您需要包裝stream_chat.Client一個界面。
如果第三方結構有很多方法,您可以將介面拆分為邏輯單元,并僅在每個處理程式中注入實際需要的那些。底層stream_chat.Client實作了所有這些,但單個模擬可以保持小并且更容易推理。就個人而言,我不認為這是值得的開銷。有很多開源模擬生成器,尤其是mockandmockgen,還有從結構生成介面的工具。
有沒有辦法將 gin.HandlerFunc,即 func(c *gin.Context) 與 stream_chat.Client 的創建正確解耦?
你有幾個選項,你可以在這里找到:如何使用 Gin Web 框架將引數傳遞給 Golang 中的路由器處理程式?
簡而言之,由于更好的單元可測驗性,我更喜歡的選項是:
- 制作結構的處理程式方法和此結構的依賴項欄位。
- 使用提供者模式并將提供者設定到中間件的 Gin 背景關系中
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/443010.html
