I am mocking my HTTP calls during tests with Gock and it works well unless I run the HTTP call from a separate goroutine (think go Post("https://myapi.com", "this body"
). I don't really care about the HTTP response in this case and just want to fire the request.
This results in a race condition between http.Client.send()
and gock.New()
. Is there a way around it or what is the recommended way to mock the API calls in this case?
Thanks!
You can use TestMain
with the following construct:
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
}