如何测试 go 中的并发任务?使用 channel 同步 goroutine:创建一个 goroutine 发送数据到 channel。在主 goroutine 中接收数据并验证。模拟并发性:当无法控制并发函数的执行时,使用 mock 或 stub。

Golang 函数:测试并发任务执行的正确性
在 Go 中,并发性是通过 goroutine 实现的。goroutine 是轻量级线程,可以在单独的 CPU 上并行执行任务。测试并发函数可以是一项具有挑战性的任务,因为您需要确保goroutine以正确的方式执行,并得到预期的结果。
使用 channel 同步 goroutine
立即学习“go语言免费学习笔记(深入)”;
channel 是在 goroutine 之间安全传递数据的首选方式。要测试使用 channel 的并发函数,您可以使用以下步骤:
- 创建一个 goroutine,它将一些数据发送到 channel。
- 在主 goroutine 中,从channel 接收数据并进行验证。
示例:
import (
"sync"
"testing"
"time"
)
func TestSendDataToChannel(t *testing.T) {
c := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
time.Sleep(50 * time.Millisecond)
c <- 10
wg.Done()
}()
go func() {
defer wg.Done()
select {
case v := <-c:
if v != 10 {
t.Errorf("Expected 10, got %d", v)
}
case <-time.After(100 * time.Millisecond):
t.Errorf("Timeout waiting for data")
}
}()
wg.Wait()
}模拟并发性
有时,您可能无法控制并发函数的执行。在这种情况下,您可以使用 mock 或 stub 来模拟并发性。
示例:
import (
"sync"
"testing"
)
type MockGoroutine struct {
wg *sync.WaitGroup
done bool
}
func (m *MockGoroutine) Start() {
go func() {
m.done = true
m.wg.Done()
}()
}
func (m *MockGoroutine) Wait() {
m.wg.Wait()
}
func (m *MockGoroutine) IsDone() bool {
return m.done
}
func TestConcurrentFunction(t *testing.T) {
wg := &sync.WaitGroup{}
goroutine := MockGoroutine{wg: wg}
goroutine.Start()
// 测试 goroutine 是否已启动
if !goroutine.IsDone() {
t.Errorf("Expected goroutine to be running")
}
// 等待 goroutine 完成
goroutine.Wait()
// 测试 goroutine 是否已完成
if goroutine.IsDone() {
t.Errorf("Expected goroutine to be finished")
}
}










