I am developing an web app with Go. So far so good, but now I am integrating Wercker as a CI tool and started caring about testing. But my app relies heavily on Cobra/Viper configuration/flags/environment_variables scheme, and I do not know how to properly init Viper values before running my test suite. Any help would be much appreciated.
问问题
9301 次
2 回答
17
当我使用 Cobra/Viper 或 CLI 帮助程序的任何其他组合时,我这样做的方法是让 CLI 工具运行一个函数,其唯一目的是获取参数并将它们传递给另一个将执行实际工作的方法。
这是一个使用 Cobra 的简短(愚蠢)示例:
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
很容易。
于 2016-03-06T14:08:03.733 回答
1
我找到了一种简单的方法来测试具有多级子命令的命令,它不专业,但效果很好。
假设我们有这样的命令
RootCmd = &cobra.Command{
Use: "cliName",
Short: "Desc",
}
SubCmd = &cobra.Command{
Use: "subName",
Short: "Desc",
}
subOfSubCmd = &cobra.Command{
Use: "subOfSub",
Short: "Desc",
Run: Exec
}
//commands relationship
RootCmd.AddCommand(SubCmd)
SubCmd.AddCommand(subOfSubCmd)
在测试 subOfSubCmd 时,我们可以这样做:
func TestCmd(t *testing.T) {
convey.Convey("test cmd", t, func() {
args := []string{"subName", "subOfSub"}
RootCmd.SetArgs(args)
RootCmd.Execute()
})
}
于 2019-07-23T06:34:34.757 回答