Demo: injecting a Clock to test time-dependent logic
On This Lesson 3 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
make "is the sale active now?" testable; prepares JNR-010-LAB1.
Draft outline details
Step by step
- Show
PromotionServicecallingLocalDate.now(); the test passes only on certain days. - Add a
Clockbean in a@Configurationclass. - Inject
Clockthrough the constructor and useLocalDate.now(clock). - Planned mistake: leave one static
Instant.now()in another service; the test still flakes. Fix: search fornow()and replace. - In the test use
Clock.fixed(...)and assert both sides of the deadline.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.