onsi / ginkgo

A Modern Testing Framework for Go
http://onsi.github.io/ginkgo/
MIT License
8.22k stars 650 forks source link

Does the eventually matcher support this usage? #1274

Closed myzhan closed 12 months ago

myzhan commented 12 months ago

I write a testcase like this, and expect it to pass. But it's not.

a := false
go func() {
    a = true
}()
Eventually(a).Should(BeTrue())

Until I rewrite it like this.

a := int32(0)
go func() {
    atomic.StoreInt32(&callbackCalled, 1)
}()
Eventually(func() int32 { return atomic.LoadInt32(&a) }).Should(BeEquivalentTo(1))
onsi commented 12 months ago

in the first example you are passing a by value so a copy of its contents is made. in the second example the function closure captures a. you could replace a with a pointer in the first example but you shouldn’t do that as it will trigger the race detector. your second example is the way to go (alternatively you can use channels)

myzhan commented 12 months ago

Ah, now I see, thanks.