A simple fake clock for Go that replaces the standard time package with an injectable interface for testing.
Clockwork is a Go library that provides a fake clock implementation for testing time-dependent code. It replaces direct usage of the standard `time` package with an injectable `Clock` interface, allowing developers to control time in unit tests. This solves the problem of flaky tests caused by real-time delays and enables deterministic testing of time-based logic.
Go developers writing unit tests for applications with time-dependent behavior, such as schedulers, timeouts, retries, or any code that uses `time.Sleep`, `time.After`, or `time.Now`.
Developers choose Clockwork because it provides a simple, idiomatic way to mock time in Go tests without complex setup. Its clean interface and fake clock implementation make it easy to write reliable, deterministic tests, and it integrates seamlessly with existing Go testing patterns.
a fake clock for golang
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Defines a simple Clock interface that abstracts time operations like Sleep and Now, making code testable by allowing easy swapping between real and fake clocks without altering logic.
FakeClock enables manual time advancement, pausing, and precise control, as shown in the example where Advance eliminates real-time waits, ensuring reliable and fast unit tests.
RealClock delegates to the standard time package, so the same injected interface works in both tests and production, avoiding code duplication or conditional logic.
Includes BlockUntilContext to synchronize goroutines in tests, preventing race conditions in time-dependent concurrent code, as demonstrated in the usage example.
Requires refactoring existing code to inject the clock interface, which can be time-consuming and introduce errors in large or legacy codebases not designed for dependency injection.
Only mocks functions from Go's time package; it doesn't cover external time sources or platform-specific APIs, which may need additional mocking strategies.
Setting up FakeClock and using synchronization methods like BlockUntilContext can increase test boilerplate and complexity, especially for simple time-based functions.