簡體   English   中英

如何在沒有等待測試的情況下測試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
}

https://play.golang.org/p/zUpNXg61Wn

大多數問題“如何測試X?” 傾向於歸結為X太大了。

在您的情況下,最簡單的解決方案是不在測試中使用goroutines。 單獨測試每個功能。 將您的代碼更改為:

func Hello() {
    go updateDatabase()
    doSomething()
}

func updateDatabase() {
    // do something and store the result for example in db
}

func doSomething() {
    // do something
}

然后為updateDatabasedoSomething編寫單獨的測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM