gpt4 book ai didi

testing - 在 goroutine 中使用 Gock 和 HTTP 调用时的数据竞争

转载 作者:IT王子 更新时间:2023-10-29 01:47:32 24 4
gpt4 key购买 nike

我在使用 Gock 进行测试期间模拟我的 HTTP 调用,它运行良好,除非我从一个单独的 goroutine 运行 HTTP 调用(想想 go Post("https://myapi.com", "this body")。在这种情况下,我真的不关心 HTTP 响应,只想触发请求。

这会导致 http.Client.send()gock.New() 之间出现竞争条件。有没有办法解决这个问题,或者在这种情况下推荐的模拟 API 调用的方法是什么?

谢谢!

最佳答案

您可以使用 TestMain具有以下结构:

func setup() {
//Mock microservice
gock.New("...")

// JOB finished URI
// Mock: go Post("https://myapi.com", "this body")
gock.New("...")
// other setup
}

func cleanup() {
//Wait until all mock done/timeout
//Adjust as needed
timeoutSec := 10
for timeoutSec > 0 && gock.IsPending() {
time.Sleep(1 * time.Second)
timeoutSec--
}
}

func TestMain(m *testing.M) {
defer gock.Off()

setup()
ret := m.Run()
if ret == 0 {
cleanup()
}

os.Exit(ret)
}

func TestYourService(t *testing.T) {
//Perform testing:
// access microservice + job in separate goroutine
}

关于testing - 在 goroutine 中使用 Gock 和 HTTP 调用时的数据竞争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43683681/

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