title: Unit testing a class with a Java 8 Clock
body: <p>Java 8 introduced <code>java.time.Clock</code> which can be used as an argument to many other <code>java.time</code> objects, allowing you to inject a real or fake clock into them. For example, I know you can create a <code>Clock.fixed()</code> and then call <code>Instant.now(clock)</code> and it will return the fixed <code>Instant</code> you provided. This sounds perfect for unit testing!</p>
  
  <p>However, I'm having trouble figuring out how best to use this. I have a class, similar to the following:</p>
  
  <pre><code>public class MyClass {
      private Clock clock = Clock.systemUTC();
  
      public void method1() {
          Instant now = Instant.now(clock);
          // Do something with 'now'
      }
  }
  </code></pre>
  
  <p>Now, I want to unit test this code. I need to be able to set <code>clock</code> to produce fixed times so that I can test <code>method()</code> at different times. Clearly, I could use reflection to set the <code>clock</code> member to specific values, but it would be nice if I didn't have to resort to reflection. I could create a public <code>setClock()</code> method, but that feels wrong. I don't want to add a <code>Clock</code> argument to the method because the real code shouldn't be concerned with passing in a clock.</p>
  
  <p>What is the best approach for handling this? This is new code so I could reorganize the class.</p>
  
  <p>Edit: To clarify, I need to be able to construct a single <code>MyClass</code> object but be able to have that one object see two different clock values (as if it were a regular system clock ticking along). As such, I cannot pass a fixed clock into the constructor.</p>