# #go #go-testing #ginkgo #gomega
Вопрос:
В моем фрагменте кода ниже или https://play.golang.org/p/tLld-zNF2zp, testValue
был объявлен внутри Describe
блока, изменен в BeforeEach
блоке. Затем используется внутри.
It
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
заявлении, а внутри него?
Ответ №1:
Из документов ginkgo еще 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"))
})
})
})
})
Комментарии:
1. К сожалению, я не понимаю, как это отвечает на мой вопрос. Не могли бы вы подробнее рассказать?
Ответ №2:
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
Комментарии:
1. Спасибо за ответ. Я также протестировал свой код, и он работал так же, как и ваш. Просто, когда я использовал
debug
в своей среде разработки, журнал отладки показывалtestValue should be 0
вместоtestValue should be 3