在这里,我正在尝试在go命令行应用程序上执行BDD,这是我在go中迈出的第一步。我使用的是Ginkgo,它包装了testing.go,让你可以做更具表现力的BDD。https://github.com/onsi/ginkgo
我在读取stdout以对其进行断言时遇到了问题。
我发现在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"))
})
})发布于 2014-09-03 22:25:27
测试Stdout可能很棘手。你有多项选择。
您可以在测试期间覆盖os.Stdout:(考虑检查错误)
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"))
})
})或者,您可以将编写器传递给您的函数:
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-04 12:07:15
这是一个典型的依赖注入用例。您可以使用来自Gomega的gbytes.Buffer,并拥有类似于以下内容的单元测试:
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,在这种情况下,我建议您使用gexec来gexec.Build二进制文件,然后运行gexec.Start命令,生成的gexec.Session对象将捕获stdout,并将其作为gbytes.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
https://stackoverflow.com/questions/25609734
复制相似问题