Testing for asynchronous results without sleep in Go

前端 未结 2 1811
灰色年华
灰色年华 2021-02-19 20:01

I have quite a few components in my code that have persistent go-routines that listen for events to trigger actions. Most of the time, there is no reason (outside of testing) fo

2条回答
  •  甜味超标
    2021-02-19 20:34

    The idiomatic way is to pass a done channel along with your data to the worker go-routine. The go-routine should close the done channel and your code should wait until the channel is closed:

    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{})
    

    Using this pattern, you can also implement a timeout for your test:

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

提交回复
热议问题