如何在不等待测试的情况下在goroutine中测试结果
how to test the result in goroutine without wait in test
我在做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 中的结果,我不需要等待它完成。但在测试中,我想在完成后查看。
如果你真的想检查 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
}
"How do I test X?" 的大多数问题往往归结为 X 太大。
对于您的情况,最简单的解决方案是不在测试中使用 goroutine。单独测试每个功能。将您的代码更改为:
func Hello() {
go updateDatabase()
doSomething()
}
func updateDatabase() {
// do something and store the result for example in db
}
func doSomething() {
// do something
}
然后为 updateDatabase
和 doSomething
编写单独的测试。
我在做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 中的结果,我不需要等待它完成。但在测试中,我想在完成后查看。
如果你真的想检查 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
}
"How do I test X?" 的大多数问题往往归结为 X 太大。
对于您的情况,最简单的解决方案是不在测试中使用 goroutine。单独测试每个功能。将您的代码更改为:
func Hello() {
go updateDatabase()
doSomething()
}
func updateDatabase() {
// do something and store the result for example in db
}
func doSomething() {
// do something
}
然后为 updateDatabase
和 doSomething
编写单独的测试。