当我做golang时,有时需要在goroutine中测试结果,我在用时间。睡眠测试,我想知道是否有更好的测试方法。
假设我有一个这样的示例代码
func Hello() {
go func() {
// do something and store the result for example in db
}()
// do something
}
然后,当我测试func时,我想在goroutine中测试两个结果,我正在这样做:
func TestHello(t *testing.T) {
Hello()
time.Sleep(time.Second) // sleep for a while so that goroutine can finish
// test the result of goroutine
}
有没有更好的方法来测试?
基本上,按照实际逻辑,我不在乎goroutine中的结果,我不需要等待它完成。但在测试中,我想检查一下是否完成。
如果您确实要检查goroutine的结果,则应使用类似以下的通道:
package main
import (
"fmt"
)
func main() {
// in test
c := Hello()
if <-c != "done" {
fmt.Println("assert error")
}
// not want to check result
Hello()
}
func Hello() <-chan string {
c := make(chan string)
go func() {
fmt.Println("do something")
c <- "done"
}()
return c
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句