Testing concurrent code question 167 of 180 mid
Can you unit test code that uses the current time or a scheduler?
- No, you must sleep
- Correct: Yes, by injecting the clock and the executor: a fixed
Clockand a deterministic or manually driven executor make the behaviour reproducible - Only with a mocking framework that rewrites bytecode
- Only in integration tests
Hard-coded System.currentTimeMillis() and a privately constructed ScheduledExecutorService are
what make a class untestable. Inject both and the tests become ordinary:
- A
java.time.Clockyou can fix or advance, so expiry and timeout logic is exact. - An
Executoryou can substitute withRunnable::runto make everything synchronous, or with a deterministic scheduler that runs queued tasks when you tell it to.
This is a design answer as much as a testing one: the same injection that makes the class testable also makes it configurable and lets the application own thread lifecycle in one place. If a class creates its own threads, nobody can control them.
Quiz yourself on Testing concurrent code Suggest a correction