2 回答

TA貢獻(xiàn)1848條經(jīng)驗 獲得超2個贊
使用 go 實現(xiàn) CLI 有多種方法。這是我開發(fā)的 CLI 的基本結(jié)構(gòu),主要受 docker CLI 的影響,我也添加了單元測試。
您需要的第一件事是將 CLI 作為接口。這將在一個名為“cli”的包中。
package cli
type Cli interface {
// Have interface functions here
sayHello() error
}
這將由 2 個 cli 實現(xiàn):HelloCli(我們真正的 CLI)和 MockCli(用于單元測試)
package cli
type HelloCli struct {
}
func NewHelloCli() *HelloCli {
cli := &HelloCli{
}
return cli
}
在這里,HelloCli 將實現(xiàn) sayHello 函數(shù),如下所示。
package cli
func (cli *HelloCli) SayHello() error {
// Implement here
}
類似地,在一個名為的包中會有一個模擬 cli test,它將實現(xiàn) cli 接口,它還將實現(xiàn) sayHello 函數(shù)。
package test
type MockCli struct {
}
func NewMockCli() *HelloCli {
cli := &MockCli{
}
return cli
}
func (cli *MockCli) SayHello() error {
// Mock implementation here
}
現(xiàn)在我將展示如何添加命令。首先,我將擁有主包,這是我將添加所有新命令的地方。
package main
func newCliCommand(cli cli.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "foo <command>"
}
cmd.AddCommand(
newHelloCommand(cli),
)
return cmd
}
func main() {
helloCli := cli.NewHelloCli()
cmd := newCliCommand(helloCli)
if err := cmd.Execute(); err != nil {
// Do something here if execution fails
}
}
func newHelloCommand(cli cli.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "hello",
Short: "Prints hello",
Run: func(cmd *cobra.Command, args []string) {
if err := pkg.RunHello(cli, args[0]); err != nil {
// Do something if command fails
}
},
Example: " foo hello",
}
return cmd
}
在這里,我有一個名為hello. 接下來,我將在一個名為“pkg”的單獨包中實現(xiàn)實現(xiàn)。
package pkg
func RunHello(cli cli.Cli) error {
// Do something in this function
cli.SayHello()
return nil
}
單元測試也將包含在此包中名為hello_test.
package pkg
func TestRunHello(t *testing.T) {
mockCli := test.NewMockCli()
tests := []struct {
name string
}{
{
name: "my test 1",
},
{
name: "my test 2"
},
}
for _, tst := range tests {
t.Run(tst.name, func(t *testing.T) {
err := SayHello(mockCli)
if err != nil {
t.Errorf("error in SayHello, %v", err)
}
})
}
}
當(dāng)你執(zhí)行foo hello時,HelloCli將被傳遞給 sayHello() 函數(shù),當(dāng)你運行單元測試時,MockCli將被傳遞。

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊
你可以檢查它cobra
自己是如何做到的 - https://github.com/spf13/cobra/blob/master/command_test.go
基本上,您可以將實際的命令邏輯(運行函數(shù))重構(gòu)為一個單獨的函數(shù)并測試該函數(shù)。您可能想要正確命名您的函數(shù),而不是僅僅調(diào)用它run
。
- 2 回答
- 0 關(guān)注
- 208 瀏覽
添加回答
舉報