Middle+
How to test the printNumber function without waiting a second?
sobes.tech AI
Answer from AI
To test the printNumber function, which internally calls time.Sleep(time.Second), without actually waiting for a second, you can use dependency injection for the sleep function. Instead of directly calling time.Sleep in the code, pass the sleep function as a parameter or use an interface.
Example:
package main
import (
"fmt"
"time"
)
type Sleeper func(d time.Duration)
func printNumber(sleep Sleeper, n int) {
sleep(time.Second) // instead of directly calling time.Sleep
fmt.Println(n)
}
// In the test, pass a stub:
func main() {
fakeSleep := func(d time.Duration) {
// do nothing, to avoid waiting
}
printNumber(fakeSleep, 42) // will immediately print 42
}
Thus, in tests, you can replace the real sleep with an empty function, which speeds up testing and eliminates delays.