douhoushou8385 2017-07-21 05:51
浏览 47
已采纳

如何在gin应用程序中测试主要功能?

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条回答 默认 最新

  • duanbi2760 2017-07-21 13:53
    关注

    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
    ", err)
        }
        bodySb, err := ioutil.ReadAll(resp.Body)
        if err != nil {
                t.Fatalf("Error reading body: %v
    ", err)
        }
        body := string(bodySb)
        fmt.Printf("Body: %v
    ", 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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测