Flaky and brittle tests
On This Lesson 4 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
spot and fix tests that fail without a real bug.
Planned topics
- A flaky test passes and fails on the same code. Causes: time, test order, randomness, shared data, real network, async timing.
- Control time with an injected
Clockinstead ofLocalDate.now(). - Avoid
Thread.sleep; wait for a condition (Awaitility) or make the code synchronous in tests. - Seed or fix randomness.
- A brittle test breaks when you refactor without changing behavior: usually over-specified (too many verifies, exact strings).
Draft outline details
Demonstration
Clock fixed = Clock.fixed(Instant.parse("2025-01-15T10:00:00Z"), ZoneOffset.UTC);
var service = new CouponService(fixed);Check your understanding
Why is Thread.sleep(2000) a bad wait?
Show answer
Too slow when fast, too short when the machine is busy; it is a guess.
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.