When writing tests for functions that expect a context, don’t use context.Background to generate a context. Instead, use t.Context. This returns a context that is automatically canceled when the test exits (if you registered any functions with t.Cleanup, the context is cancelled just before they run). Using the test context allows any code under test to properly shut down. This includes goroutines that exit upon context cancellation. (In “Test Concurrent Code with synctest”, you will learn how to find goroutines that don’t shut down when the context is canceled.) Sample code that demonstrates the test context is in the examples/oracle directory:
func TestOracle(t *testing.T) {
ctx := t.Context()
ch := oracle.Launch(ctx)
outCh := make(chan string)
ch <- oracle.Request{
Query: "Is the sky blue?",
Response: outCh,
}
result := <-outCh
if result != "Is the sky blue? Yes!" {
t.Error("the oracle is wearing rose-tinted glasses")
}
}
Progress is saved on this device.