testing - how to test the result in goroutine without wait in test -
when ut of golang, need test result in goroutine, using time.sleep test, wondering there better way test.
let's have example code this
func hello() { go func() { // , store result example in db }() // }
then when test func, want test both result in goroutine, doing this:
func testhello(t *testing.t) { hello() time.sleep(time.second) // sleep while goroutine can finish // test result of goroutine }
is there better way test this?
basically, in real logic, don't care result in goroutine, don't need wait finished. in test, want check after finished.
if want check result goroutine, should using channel.
package main import ( "fmt" ) func main() { // in test c := hello() if <-c != "done" { fmt.println("assert error") } // not want check result hello() } func hello() <-chan string { c := make(chan string) go func() { fmt.println("do something") c <- "done" }() return c }
Comments
Post a Comment