gpt4 book ai didi

unit-testing - 在 Go 中测试不带 sleep 的异步结果

转载 作者:IT老高 更新时间:2023-10-28 13:10:16 26 4
gpt4 key购买 nike

我的代码中有相当多的组件具有持久的 go-routines,它们监听事件以触发操作。大多数情况下,他们没有理由(在测试之外)在完成该操作后发回通知。

但是,我的单元测试使用 sleep 来等待这些异步任务完成:

// Send notification event.
mock.devices <- []sparkapi.Device{deviceA, deviceFuncs, deviceRefresh}

// Wait for go-routine to process event.
time.Sleep(time.Microsecond)

// Check that no refresh method was called.
c.Check(mock.actionArgs, check.DeepEquals, mockFunctionCall{})

这似乎很糟糕,但我还没有想出一个更好的解决方案,它不会给非测试使用增加不合理的开销。有没有我错过的合理解决方案?

最佳答案

惯用的方法是将 done channel 与您的数据一起传递给工作程序 go-routine。 go-routine 应该 close done channel 并且您的代码应该等到 channel 关闭:

done := make(chan bool)

// Send notification event.
mock.devices <- Job {
Data: []sparkapi.Device{deviceA, deviceFuncs, deviceRefresh},
Done: done,
}

// Wait until `done` is closed.
<-done

// Check that no refresh method was called.
c.Check(mock.actionArgs, check.DeepEquals, mockFunctionCall{})

使用此模式,您还可以为您的测试实现超时:

// Wait until `done` is closed.
select {
case <-done:
case <-time.After(10 * time.Second):
panic("timeout")
}

关于unit-testing - 在 Go 中测试不带 sleep 的异步结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30427013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com