title: Mockito: what if argument passed to mock is modified?
body: <p>We came across really nasty problem with Mockito.</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>public class Baz{
      private Foo foo;
      private List list;
  
      public Baz(Foo foo){
          this.foo = foo;
      }
  
      public void invokeBar(){
          list = Arrays.asList(1,2,3);
          foo.bar(list);
          list.clear();
      }
  
  }
  
  
  public class BazTest{
  
     @Test
     void testBarIsInvoked(){
          Foo mockFoo = mock(Foo.class);
          Baz baz = new Baz(mockFoo);           
          baz.invokeBar();
          verify(mockFoo).bar(Arrays.asList(1,2,3));
     }
  }
  </code></pre>
  
  <p>This causes error message like:</p>
  
  <pre><code>Arguments are different! Wanted: 
  foo.bar([1,2,3]); 
  Actual invocation has different arguments:
  foo.bar([]);
  </code></pre>
  
  <p><strong>What just happened:</strong></p>
  
  <p>Mockito records <strong>reference</strong> to <code>list</code> rather than copy of <code>list</code>, so in the code above Mockito verifies against <em>modified version</em> (empty list, <code>[]</code>) instead to the one actually passed during invocation (<code>[1,2,3]</code>)!</p>
  
  <p><strong>Question:</strong></p>
  
  <p>Is there any elegant and clean solution to this problem other than doing a defensive copy like below (which actually helps but we don't like this solution)?</p>
  
  <pre><code>   public void fun(){
          list = Arrays.asList(1,2,3);
          foo.bar(new ArrayList(list));
          list.clear();
      }
  </code></pre>
  
  <p>We don't want to modify <strong>correct</strong> production code and <strong>reduce its performance</strong> only to fix technical problem with test.</p>
  
  <p>I'm asking this question here because it seems to be possibly common problem with Mockito. Or we just do something wrong?</p>
  
  <p>PS. This is not a real code so please don't ask why we create a list and then clear it etc. In real code we have a real need to do something similar :-).</p>