On Thu, Jan 28, 2021 at 10:15 PM Christian Worm Mortensen <c...@epust.dk> wrote:
> Suppose I want to unit test this function: > > func generator() <-chan int { > ret := make(chan int) > go func() { > for i := 0; i < 10; i++ { > ret <- i > time.Sleep(time.Second) > } > }() > return ret > } > > What is a good way to do that? > > Abstract away time.Sleep(time.Second). Set up a channel in lieu of the sleep and use that in the code instead. Because you have `select { ... }` you can even listen to multiple different events for firing should it become necessary. Some rough things: In real code, you often want a `context.Context` inside your goroutines, mainly in order to be able to tear down goroutine networks once they aren't useful anymore. This sets up the code neatly for a channel based approach. In real code, you often want something to progress based on an event trigger, rather than a sleeping pattern. This can often speed up processing by quite a lot, because you can do something as soon as you are ready to do it. In real code, there is a chance you can arrange the above code such that your goroutine never sleeps, but the sleep is on the receiver side. This can improve parallelism and also open up the possibility of latency hiding in the communication. As a general rule: you often want time to be an injected parameter in a system rather than something the system asks for when it's needed. The reason being that you now control time in the test scenario[0]. This often generalizes to communication. [0] Aside: There's a clear similarity to linear logic here. In a two-agent LL system, choice can be made either by the test harness or by the system-under-test. You usually want to move as much choice onto the side of the test-harness as to minimize the need for extensive mocking in your program. In LL, there's two "or-operators" corresponding to disjunction of each party. -- J. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAGrdgiUXZ%2BxHLiK97sO%2BCA4%3Dr0RKUSsYaLQJXPbsd5_EW_O4oA%40mail.gmail.com.