Ginkgo是一个BDD风格的Go测试框架,旨在帮助您有效地编写富有表现力的综合测试。
$ go get github.com/onsi/ginkgo/ginkgo
$ go get github.com/onsi/gomega/...
$ go env |grep -i gopath
GOPATH="/usr/local/gopath"
$ cd /usr/local/gopath/src
$ mkdir books
$ cd books
$ ginkgo bootstrap
$ ls
books_suite_test.go
$ cat books_suite_test.go
package books_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestBooks(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Books Suite")
}
$ vim books.go
package books
type Book struct {
Title string
Author string
Pages int
}
func (b *Book) CategoryByLength() string {
if b.Pages >= 300 {
return "NOVEL"
}
return "SHORT STORY"
}
$ ginkgo
Failed to compile books:
go: cannot find main module; see 'go help modules'
Ginkgo ran 1 suite in 53.915004ms
Test Suite Failed
$ go mod init
go: creating new go.mod: module books
$ ginkgo
Running Suite: Books Suite
==========================
Random Seed: 1595924522
Will run 0 of 0 specs
Ran 0 of 0 Specs in 0.000 seconds
SUCCESS! -- 0 Passed | 0 Failed | 0 Pending | 0 Skipped
PASS
Ginkgo ran 1 suite in 1.028037658s
Test Suite Passed
分析:
一个空的测试套件不是很有趣。虽然您可以开始直接将测试添加到books_suite_test.go中,但您可能更愿意将测试分成单独的文件(特别是对于包含多个文件的包)。让我们为book.go模型添加一个测试文件:
$ ginkgo generate book
Generating ginkgo test for Book in:
book_test.go
$ cat book_test.go
package books_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"books"
)
var _ = Describe("Book", func() {
})
分析:
Describe 中的功能将包含我们的Specs。现在让我们添加一些来测试从JSON中加载books:
books_test.go
package books_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
//"books"
)
type Book struct {
Title string
Author string
Pages int
}
func (b *Book) CategoryByLength() string {
if b.Pages >= 300 {
return "NOVEL"
}
return "SHORT STORY"
}
var _ = Describe("Book", func() {
var (
longBook Book
shortBook Book
)
BeforeEach(func() {
longBook = Book{
Title: "Les Miserables",
Author: "Victor Hugo",
Pages: 1488,
}
shortBook = Book{
Title: "Fox In Socks",
Author: "Dr. Seuss",
Pages: 24,
}
})
Describe("Categorizing book length", func() {
Context("With more than 300 pages", func() {
It("should be a novel", func() {
Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
})
})
Context("With fewer than 300 pages", func() {
It("should be a short story", func() {
Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
})
})
})
})
分析 :
$ ginkgo
Running Suite: Books Suite
==========================
Random Seed: 1595926303
Will run 2 of 2 specs
••
Ran 2 of 2 Specs in 0.001 seconds
SUCCESS! -- 2 Passed | 0 Failed | 0 Pending | 0 Skipped
PASS
Ginkgo ran 1 suite in 1.108253073s
Test Suite Passed