title: How to Unit Test a Time-related State Machine Using Mockito in Java
body: <p>I have written a class called <code>ErrorHandingFiniteStateMachine</code>, which basically does something like:</p>
  
  <p><a href="https://developers.google.com/safe-browsing/developers_guide_v3#RequestFrequencyHashes" rel="nofollow">https://developers.google.com/safe-browsing/developers_guide_v3#RequestFrequencyHashes</a></p>
  
  <p>Basically it has a function called <code>ErrorHandlingFiniteStateMachine.update()</code>, which will be called when the caller class receives an error. It will then update the error state, which depends on:</p>
  
  <ul>
  <li>how many errors it has received;</li>
  <li>how much time it has elapsed since last error;</li>
  <li>and of course, the last error state.</li>
  </ul>
  
  <p>Now my questions are:</p>
  
  <ol>
  <li>How to mock up the time elapsed in <code>mockito</code>, because the time can be very long, such as hours, and I definitely don't want to wait for several hours to finish a unit test.</li>
  <li>Is there any standard tutorial or best practice to test a state machine with time-related features?</li>
  </ol>
  
  <p><strong>EDIT</strong></p>
  
  <p>As folks pointed out, I use <code>System.currentTimeMillis</code> to remember the current timestamp. But BTW, the unit test is not supposed to know so much detailed info about the implementation, right?</p>
  
  <p><strong>MY SOLUTION</strong></p>
  
  <p>I finally wrapped <code>System.currentTimeMillis()</code> in the <code>ErrorHandlingFiniteStateMachine.getCurrentTimestamp()</code>, and make it package-private (no modifier), so it's accessible in my <code>TestErrorHandlingFiniteStateMachine</code>. Then I used a <code>mockito</code> <code>spy</code> to mock the <code>ErrorHandlingFiniteStateMachine.getCurrentTimestamp()</code> </p>