Fake Clocks in Rust: How to Test Time Without Waiting
Controlling time in Rust is essential, especially when dealing with unit tests. Check out this video for the first part: https://youtu.be/6wAFdBVJbwc π Description Master dependency injection and testable time in Rust by building a fake clock for your cache. In this practical tutorial, we explore how to replace fragile `thread::sleep` calls in unit tests with a deterministic, controllable clock. We will break down exactly how the `Clock` trait works, why generics let us swap a real clock for a fake one with zero runtime cost, and how interior mutability lets us fast-forward time on demand. By the end, you will know exactly how to write cache expiration tests that run instantly and never flake. Here's what you will learn: β’ Understand why `thread::sleep` in unit tests is bad practice and how a fake clock solves it by making time fully deterministic and instant. β’ Learn how to define a `Clock` trait as a contract, so any type reporting "now" can be swapped in, whether it reads the real system clock or a value we control. β’ Discover how to make `TaxCache` generic over `C: Clock`, understanding why generics resolve at compile time for zero runtime overhead, versus the trait object alternative (`Box dyn Clock`). β’ Build a `MockClock` using `RefCell` for interior mutability, letting you mutate stored time behind an immutable reference with borrow rules checked at runtime instead of compile time. β’ Apply the pattern to a real expiration test: advance the fake clock by 61 seconds and assert the cache correctly evicts stale data, no waiting required. β³ Timestamps: 00:00 - Introduction 00:15 - Recap 01:31 - Implementation 13:54 - Outro π Hey there! If you are new to this channel: Hey π my name is Flo and I am a professional software engineer with a passion for coding in Golang, TypeScript, JavaScript, and Rust. This channel is where I share that passion and dive into the exciting world of software engineering. π¨ Support and Connect! Become a member. https://www.youtube.com/@FloWoelki/membership Discord: https://discord.gg/TnA7drJ X / Twitter: https://x.com/FlorianWoelki LinkedIn: https://www.linkedin.com/in/florian-woelki/ GitHub: https://github.com/FlorianWoelki π Copyright Notice The original Ferris mascot was designed by Karen Rustad TΓΆlva and released into the public domain under CC0 1.0 (Source: https://rustacean.net/). The Ferris appearing in this video and thumbnail has been modified from the original design and is based on an illustration from Maria Letta's free-ferris-pack (Source: https://github.com/MariaLetta/free-ferris-pack; License: CC0 1.0 Public Domain https://creativecommons.org/publicdomain/zero/1.0/). #rust #clock #time




Join the discussion
Sign in to join the discussion
Sign in