Middle+
Kuidas testida funktsiooni printNumber ilma ühe sekundi ootamata?
sobes.tech AI
Vastus AI-lt
To test the printNumber function, which internally calls time.Sleep(time.Second) without actually waiting 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
}
This way, in tests, the real sleep can be replaced with an empty function, speeding up tests and removing delays.