测试 Golang Goroutine

我一直在四处寻找,但到目前为止,只有Ariejan de Vroom在这里写过类似的文章。


我想知道我是否可以将 goroutine 引入单元测试,以便它可以精确计算正在运行的 goroutine 的并发数量,并可以告诉我它们是否按照我所说的数量正确生成了 goroutine。


例如,我有以下代码..


import (

    "testing"

    "github.com/stretchr/testify/assert"

)


func createList(job int, done chan bool) {

    time.Sleep(500)

    // do something

    time.Sleep(500)

    done <- true

    return

}


func TestNewList(t *testing.T) {

  list := NewList()

  if assert.NotNil(t, list) {

    const numGoRoutines = 16

    jobs := make(chan int, numGoRoutines)

    done := make(chan bool, 1)


    for j := 1; j <= numGoRoutines; j++ {

        jobs <- j

        go createList(j, done)

        fmt.Println("sent job", j)

    }

    close(jobs)

    fmt.Println("sent all jobs")

    <-done

}


www说
浏览 233回答 2
2回答

慕村9548890

据我了解,您愿意限制同时运行的例程数量并验证它是否正常工作。我建议编写一个函数,它将一个例程作为参数并使用模拟例程来测试它。在下面的示例中,spawn函数运行fn例程count次数,但不超过limit例程并发。我将它包装到 main 函数中以在操场上运行它,但您可以对您的测试方法使用相同的方法。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func spawn(fn func(), count int, limit int) {&nbsp; &nbsp; limiter := make(chan bool, limit)&nbsp; &nbsp; spawned := func() {&nbsp; &nbsp; &nbsp; &nbsp; defer func() { <-limiter }()&nbsp; &nbsp; &nbsp; &nbsp; fn()&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < count; i++ {&nbsp; &nbsp; &nbsp; &nbsp; limiter <- true&nbsp; &nbsp; &nbsp; &nbsp; go spawned()&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; count := 10&nbsp; &nbsp; limit := 3&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(count)&nbsp; &nbsp; concurrentCount := 0&nbsp; &nbsp; failed := false&nbsp; &nbsp; var mock = func() {&nbsp; &nbsp; &nbsp; &nbsp; defer func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; concurrentCount--&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; concurrentCount++&nbsp; &nbsp; &nbsp; &nbsp; if concurrentCount > limit {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; failed = true // test could be failed here without waiting all routines finish&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(100)&nbsp; &nbsp; }&nbsp; &nbsp; spawn(mock, count, limit)&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; if failed {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Test failed")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Test passed")&nbsp; &nbsp; }}

红颜莎娜

一种可能的方法是使用runtime.Stack()或分析 的输出,runtime.debug.PrintStack()以便在给定时间查看所有 goroutine。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go