Java Concurrency Interview

Testing concurrent code question 167 of 180 mid

Can you unit test code that uses the current time or a scheduler?

Hard-coded System.currentTimeMillis() and a privately constructed ScheduledExecutorService are what make a class untestable. Inject both and the tests become ordinary:

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.

testing design

Quiz yourself on Testing concurrent code Suggest a correction