-1

在我下面的代码片段或https://play.golang.org/p/tLld-zNF2zp中,在块testValue内声明Describe,在块内更改BeforeEach。然后,用在。

  1. It
  2. Expect

测试按预期通过。从调试日志中,It总是显示testValue should be 0而不是testValue should be 3

package awesomeProject1_test

import (
    "fmt"
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
)

var _ = Describe("AwesomeProject1", func() {
    var testValue int
    BeforeEach(func() {
        testValue = 3
    })
    Context("Correctness of testValue", func() {
        It(fmt.Sprintf("testValue should be %d", testValue), func() {
            Expect(testValue).To(Equal(3))
        })
    })
})

为什么testValue不是在It语句中改变而是在它里面?

4

2 回答 2

0
package ginkgo_test

import (
    "fmt"
    "testing"

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

var _ = Describe("AwesomeProject1", func() {
    var testValue int
    BeforeEach(func() {
        testValue = 3
    })
    Context("Correctness of testValue", func() {
        It(fmt.Sprintf("testValue should be %d", testValue), func() {
            Expect(testValue).To(Equal(3))
        })
    })
})

func TestGoStudy(t *testing.T) {
    RegisterFailHandler(Fail)
    RunSpecs(t, "GoStudy Suite")
}
=== RUN   TestGoStudy
Running Suite: GoStudy Suite
============================
Random Seed: 1634629701
Will run 1 of 1 specs

•
Ran 1 of 1 Specs in 0.000 seconds
SUCCESS! -- 1 Passed | 0 Failed | 0 Pending | 0 Skipped
--- PASS: TestGoStudy (0.00s)
PASS

Process finished with the exit code 0

我已经测试了您的代码并且代码运行良好。

我的测试环境:

go version go1.17.1
github.com/onsi/ginkgo v1.16.5 
github.com/onsi/gomega v1.16.0 
于 2021-10-19T07:56:21.933 回答
0

ginkgo docs,另一个Describe包装Context函数:

var _ = Describe("Book", func() {
    var (
        longBook  Book
        shortBook Book
    )

    BeforeEach(func() {
        longBook = Book{
            Title:  "Les Miserables",
            Author: "Victor Hugo",
            Pages:  2783,
        }

        shortBook = Book{
            Title:  "Fox In Socks",
            Author: "Dr. Seuss",
            Pages:  24,
        }
    })

    //Describe wrapping context
    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"))
            })
        })
    })
})
于 2021-10-19T06:54:17.650 回答