title: How to test expiration conditions?
body: <p>I'm developing a component that provides tokens that have a limited lifespan and need not be persisted in case of application restart. Hence, the tokens are only stored in memory. Each token is identified by a key and have an associated time-to-live after which the token expires and can no longer be used. </p>
  
  <p>I halted to think how would you go about testing that the expiration conditions work as planned?</p>
  
  <ol>
  <li>The naïve implementation using <code>System.currentTimeMillis</code> does not provide a proper way to inject arbitary times to test the boundaries.</li>
  <li>Adding a datetime parameter (<code>Calendar</code>, Joda-Time's <code>DateTime</code>, etc) to the appropriate methods does not make sense outside of the testing context as it's not the responsibility of the caller to know what time it is. </li>
  <li>Wrapping the system time in a class that can be injected and mocked seems the way to go but feels a bit cumbersome. This would also require another constructor as a default implemention suffice in all but testing circumstances.  </li>
  <li>Defining the lifespan as a setting would allow making the wait short enough to make a <code>sleep()</code> or a busy-wait a reasonable and reliable solution</li>
  </ol>
  
  <p>I'm currently leaning towards option 4 but I'd learn about more options as well!</p>
  
  <p>Overly simplified scribbled scenario: </p>
  
  <pre><code>private static final long LIFE_SPAN = 60000;
  private Map&lt;T, Long&gt; bestBeforeDates = new HashMap&lt;T, Long&gt;();
  
  public void add(final T key) {
     bestBeforeDates.put(key, System.currentTimeMillis() + LIFE_SPAN);
  }
  
  public boolean isExpired(final T key) {
    // How to make this fail without waiting for x milliseconds
    return bestBeforeDates.get(key) &lt; System.currentTimeMillis();    
  }
  </code></pre>