6

在这里,我正在尝试在 go 命令行应用程序上执行 BDD 的第一步。我正在使用 Ginkgo,它包装了 testing.go,让你做更具表现力的 BDD。https://github.com/onsi/ginkgo

我在阅读标准输出以对其进行断言时遇到问题。

发现pkg/testing示例在运行之前对输出进行存根,但我找不到读取该输出的方法:http: //golang.org/src/pkg/testing/example.go

这就是我想做的:

cli.go

 package cli
  
 import "fmt"
  
 func Run() {
        fmt.Println("Running cli")
 }

cli_test.go

package cli_test

import (
        . "github.com/altoros/bosh_deployer_cli/lib/cli"

        . "github.com/onsi/ginkgo"
        . "github.com/onsi/gomega"
)

var _ = Describe("Cli", func() {
        It("should parse update stemcell flag", func() {
                Run()
                Expect(stdout).To(Equal("running cli"))
        })
})
4

2 回答 2

8

Testing Stdout can be tricky. You have multiple choice.

You can override os.Stdout during your test: (think to check the errors)

var _ = Describe("Cli", func() {
        It("should parse update stemcell flag", func() {
                r, w, _ := os.Pipe()
                tmp := os.Stdout
                defer func() {
                        os.Stdout = tmp
                }()
                os.Stdout = w
                go func() {
                        Run()
                        w.Close()
                }()
                stdout, _ := ioutil.ReadAll(r)
                Expect(string(stdout)).To(Equal("Running cli\n"))
        })
})

or you can pass a writer to your function:

cli.go

package cli

import (
        "fmt"
        "io"
)

func Run(w io.Writer) {
        fmt.Fprintln(w, "Running cli")
}

cli_test.go

package cli_test

import (
        . "cli"
        "io"
        "io/ioutil"

        . "github.com/onsi/ginkgo"
        . "github.com/onsi/gomega"
)

var _ = Describe("Cli", func() {
        It("should parse update stemcell flag", func() {
                r, w := io.Pipe()
                go func() {
                        Run(w)
                        w.Close()
                }()
                stdout, _ := ioutil.ReadAll(r)
                Expect(string(stdout)).To(Equal("Running cli\n"))
        })
})

main.go

package main

import (
        "cli"
        "os"
)

func main() {
        cli.Run(os.Stdout)
}
于 2014-09-03T14:25:27.170 回答
4

这是依赖注入的经典用例。您可以使用gbytes.BufferfromGomega并使用以下内容进行单元测试:

var _ = Describe("Cli", func() {
        It("should parse update stemcell flag", func() {
                buffer := gbytes.NewBuffer()
                Run(buffer)
                Expect(buffer).To(gbytes.Say("Running cli\n"))
        })
})

除非您正在对. cli_ _ _gexecgexec.Buildgexec.Startgexec.Sessionstdoutgbytes.Buffer

Expect(session).To(gbytes.Say("Running cli\n")

更多细节在gbytes这里gexec

http://onsi.github.io/gomega/#gbytes-testing-streaming-buffers

http://onsi.github.io/gomega/#gexec-testing-external-processes

于 2014-09-04T04:07:14.993 回答