2016-03-06 34 views
6

我正在用Go開發一個Web應用程序。目前爲止這麼好,但現在我正在將Wercker作爲CI工具並開始關注測試。但是我的應用很大程度上依賴於Cobra/Viper配置/ flags/environment_variables方案,並且我不知道如何在運行測試套件之前正確初始化Viper值。任何幫助將非常感激。Cobra + Viper Golang如何測試子命令?

回答

6

當我使用Cobra/Viper或CLI助手的任何其他組合時,我的做法是讓CLI工具運行一個函數,其唯一目的是獲取參數並將它們傳遞給另一個將執行實際工作。

下面是使用眼鏡蛇短(和啞)例如:

package main 

import (
     "fmt" 
     "os" 

     "github.com/spf13/cobra" 
) 

func main() { 
     var Cmd = &cobra.Command{ 
       Use: "boom", 
       Short: "Explode all the things!", 
       Run: Boom, 
     } 

     if err := Cmd.Execute(); err != nil { 
       fmt.Println(err) 
       os.Exit(-1) 
     } 
} 

func Boom(cmd *cobra.Command, args []string) { 
     boom(args...) 
} 

func boom(args ...string) { 
     for _, arg := range args { 
       println("boom " + arg) 
     } 
} 

這裏,Boom功能難以測試,但boom一個是容易的。

您可以看到here(和相應的測試here)的另一個(非啞巴)示例。