title: Mocking Calendar.getInstance static method multiple times in a method
body: <p>I am currently using JMockito/PowerMock so that I can mock the return value of a static method, in this case, Calendar.getInstance().
  My issue is very similar to this, but not quite:
  <a href="https://stackoverflow.com/questions/14456377/powermocking-static-does-not-return-expected-object">PowerMocking static does not return expected object</a></p>
  
  <p>I have also checked various other similar topics but none of them quite falls into my context. Currently, I have a code that like this:</p>
  
  <pre><code>Calendar cal = Calendar.getInstance();
  //modifies this instance
  .....
  .....
  //then there is another call:
  cal2 = Calendar.getInstance();
  ....
  ....
  </code></pre>
  
  <p>What the logic does is not important here. When I have tried testing this block of method, I have expectation like so:</p>
  
  <pre><code>Calendar myOwn = //whatever
  when(Calendar.getInstance()).thenReturn(myOwn);
  </code></pre>
  
  <p>So during test what happens testing is that in the first call of <code>Calendar.getInstance()</code> it manages to successfully get <code>myOwn</code> object which is what I expect. And obviously, the method then does some modification to this object.</p>
  
  <p><strong>However</strong>, while debugging, when the next call <code>Calendar.getInstance()</code> happens later, the variable <code>cal2</code> seems to get the modified version of <code>myOwn</code> object from before. I would have thought that it would get the <em>original</em> <code>myOwn</code> calendar object but it doesn't.</p>
  
  <p>I have also tried rebuilding the expectation to this (because there is a total of two <code>getInstance()</code> calls, at least in this method):</p>
  
  <pre><code>when(Calendar.getInstance()).thenReturn(myOwn).theReturn(myOwn);
  </code></pre>
  
  <p>but no luck. Then I thought whether this was an issue of variable getting passed by reference due to it being static however, the following output is valid and perfectly logical too as I tested it in isolation.</p>
  
  <pre><code>Calendar cal = Calendar.getInstance();
  System.out.println(cal.getTime()); //prints current date object (as expected)
  
  cal.set(Calendar.YEAR, 2017);
  System.out.println(cal.getTime()); //prints modified timestamp of 2017 (as expected)
  
  //new instance
  Calendar cal2 = Calendar.getInstance();
  System.out.println(cal2.getTime()); //still prints current date object (as expected)
  </code></pre>
  
  <p>I can easily fix my test if I clone the second instance of calendar object in code from previous before it gets modified. But this involve modifying existing source code which I can't as it's quite a legacy code.</p>
  
  <p>So what have I done wrong in my unit test with this static method? I have also tried testing with JMockit and still get the same issue. Pretty sure it's something obvious but cannot figure it out. Thank you for your time.</p>