我一直在到处寻找,但到目前为止只有Ariejan de Vroom写的类似的here文章。
我想知道我是否可以在单元测试中引入goroutine,这样它就可以精确地计算正在运行的goroutines的并发数量,并且可以告诉我它们是否正确地产生了我所说的数量的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
}发布于 2015-03-07 19:55:48
据我所知,您愿意限制同时运行的例程的数量,并验证它是否正常工作。我建议写一个函数,它将一个例程作为参数,并使用模拟例程来测试它。
在下面的示例中,spawn函数运行fn例程count次,但并发次数不超过limit例程。我将它封装到main函数中,以便在游乐场上运行它,但是您可以对您的测试方法使用相同的方法。
package main
import (
"fmt"
"sync"
"time"
)
func spawn(fn func(), count int, limit int) {
limiter := make(chan bool, limit)
spawned := func() {
defer func() { <-limiter }()
fn()
}
for i := 0; i < count; i++ {
limiter <- true
go spawned()
}
}
func main() {
count := 10
limit := 3
var wg sync.WaitGroup
wg.Add(count)
concurrentCount := 0
failed := false
var mock = func() {
defer func() {
wg.Done()
concurrentCount--
}()
concurrentCount++
if concurrentCount > limit {
failed = true // test could be failed here without waiting all routines finish
}
time.Sleep(100)
}
spawn(mock, count, limit)
wg.Wait()
if failed {
fmt.Println("Test failed")
} else {
fmt.Println("Test passed")
}
}Playground
发布于 2015-03-05 15:02:36
一种可能的方法是使用runtime.Stack()或分析runtime.debug.PrintStack()的输出,以便在给定时间查看所有goroutines。
这些选项在"How to dump goroutine stacktraces?“中有详细介绍。
https://stackoverflow.com/questions/28868596
复制相似问题