The best way (IMO) of making your code testable is to extract the dependency of "what's the current time" into its own interface, with an implementation which uses the current system time (used normally) and an implementation which lets you set the time, advance it as you want etc.
I've used this approach in various situations, and it's worked well. It's easy to set up - just create an interface (e.g. Clock
) which has a single method to give you the current instant in whatever format you want (e.g. using Joda Time, or possibly a Date
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…