英文:
How to test main function in gin application?
问题
你好!以下是翻译好的内容:
如何测试 func main
函数?像这样:
func main(){
Engine := GetEngine() // 返回带有处理程序的 gin 路由器
Engine.Run(":8080")
}
这段代码只有两行,但我想要对它们进行测试覆盖。TestMain
用于测试准备工作,这是否意味着语言创建者没有计划测试 main
函数?我可以将内容移动到另一个函数 mainReal
中,但这似乎有点过度设计?
如何测试 gin 是否成功启动?我可以在单独的 goroutine 中启动 main
函数,检查回复并停止它吗?
谢谢。
P.S. 可能的重复问题并不是精确的重复,因为它专门用于测试 func main()
本身,而是关于将其移至外部的想法,因此涉及不同的问题和方法。
英文:
How can I test func main
? Like this:
func main(){
Engine := GetEngine() // returns gin router with handlers atttached
Engine.Run(":8080")
}
It has only 2 lines but I'd like to have them covered.
TestMain'
is reserved for test preparation, does that mean testing main
was not planned by language creators?
I can move the contents to another function mainReal
but it seems to be some over engineering?
How to test gin has started well? Can I launch main
in separate goroutine, check reply and stop it?
Thanks.
P.S. Possible duplicate is not precise duplicate because it is dedicated not to testing of func main()
itself, but rather ideas to move in outside and so contains different issue and approach.
答案1
得分: 0
解决方案。
您可以以与之前相同的方式测试main
包中的main()
函数,只是不要将其命名为TestMain
。我将其作为一个单独的goroutine启动,然后尝试连接并执行任何请求。
我决定连接到辅助处理程序,该处理程序应该以简单的JSON { "status": "ok" }
进行响应。
在我的情况下:
func TestMainExecution(t *testing.T) {
go main()
resp, err := http.Get("http://127.0.0.1:8080/checkHealth")
if err != nil {
t.Fatalf("Cannot make get: %v\n", err)
}
bodySb, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error reading body: %v\n", err)
}
body := string(bodySb)
fmt.Printf("Body: %v\n", body)
var decodedResponse interface{}
err = json.Unmarshal(bodySb, &decodedResponse)
if err != nil {
t.Fatalf("Cannot decode response <%p> from server. Err: %v", bodySb, err)
}
assert.Equal(t, map[string]interface{}{"status": "ok"}, decodedResponse,
"Should return status:ok")
}
英文:
Solution.
You may test function main()
from package main
the same way, just do not name it TestMain
. I launch it as a separate goroutine, than try to connect to it and perform any request.
I decided to connect to auxilary handler which should respond with a simple json {"status": "ok"}
.
In my case:
func TestMainExecution(t *testing.T) {
go main()
resp, err := http.Get("http://127.0.0.1:8080/checkHealth")
if err != nil {
t.Fatalf("Cannot make get: %v\n", err)
}
bodySb, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error reading body: %v\n", err)
}
body := string(bodySb)
fmt.Printf("Body: %v\n", body)
var decodedResponse interface{}
err = json.Unmarshal(bodySb, &decodedResponse)
if err != nil {
t.Fatalf("Cannot decode response <%p> from server. Err: %v", bodySb, err)
}
assert.Equal(t, map[string]interface{}{"status": "ok"}, decodedResponse,
"Should return status:ok")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论