java - Is it possible to freeze System.currentTimeMillis() for testing -


for testing purposes predict system.currenttimemillis() return. there way in can freeze or manually set return when system.currenttimemillis() called?

i suggest avoid using system.currenttimemillis (and new date() etc) in general code.

instead, create clock interface representing "a service give current time" , create 1 implementation does use system.currenttimemillis or whatever, , fake implementation can control explicitly.

use dependency injection make instance of service available code needs it. in production, use system.currenttimemillis version, , in testing use fake.

this gives ability not stop time, set whatever want - can have static test data know never expire, , can test tricky things around boundaries etc. i've used approach in many projects, extent in noda time project it's the way of getting @ "the current time".

note if you're doing serious amount of time work in java, i'd recommend using joda time, , making clock interface return instant:

public interface clock {     instant now(); } 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -