当我使用golang时,我有时需要在goroutine中测试结果,我正在使用time.Sleep进行测试,我想知道是否有更好的测试方法。
假设我有一个像这样的示例代码
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的结果,我不需要等待它完成。但在测试中,我想在完成后检查。
答案 0 :(得分:3)
如果你真的想检查结果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
}
答案 1 :(得分:2)
“如何测试X?”的大多数问题往往会归结为 X 过大。
在您的情况下,最简单的解决方案是不在测试中使用goroutines。单独测试每个功能。将您的代码更改为:
func Hello() {
go updateDatabase()
doSomething()
}
func updateDatabase() {
// do something and store the result for example in db
}
func doSomething() {
// do something
}
然后为updateDatabase
和doSomething
编写单独的测试。