title: Mockito: save mock argument and return it from another function
body: <p>I want to implement something like this construction.</p>
  
  <p>Main class:</p>
  
  <pre><code>public class Connection {
  
      byte[] read() throws Exception 
      {
        // read some data
        return data;
      }
  
      void write(byte[] data) throws Exception 
      {
        // write some data
      }
  }
  </code></pre>
  
  <p>Test class:</p>
  
  <pre><code>public class ConnectionTest 
  {
      private static byte[] mockData;
      private Connection connection;
  
      public Connection createMockConnection() {
          Connection mockConnection = mock(Connection.class);
  
          try {
              doAnswer(new Answer() {
                  @Override
                  public Object answer(InvocationOnMock invocation) throws Throwable {
                      mockData = (byte[]) invocation.getArguments()[0];
                      return mockData;
                  }
              }).when(mockConnection).write(any(byte[].class));
  
              when(mockConnection.read()).thenReturn(mockData);
          } catch (Exception e) {}
  
          return mockConnection;
      }
  
      @Before
      public void createConnection() throws Exception {
          connection = createMockConnection();
      }
  
      @After
      public void destroyConnection() throws Exception {
          connection = null;
      }
  
      @Test
      public void testCallbackConnection() throws Exception {
          byte[] data = new byte[] {1,2,3,4};
          connection.write(data);
  
          assertArrayEquals(data, connection.read());
     }
  </code></pre>
  
  <p>Saved value <code>mockData</code> doesn't contains actual data buffer when I stubbing <code>write()</code> and <code>read()</code> methods. How I can get actual value passed in <code>testCallbackConnection()</code> function? </p>
  
  <p>Thank you!</p>
  
  <p><strong>UPDATE:</strong> </p>
  
  <p>I mock write() and read() methods in createMockConnection() function:</p>
  
  <pre><code>doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
          mockData = (byte[]) invocation.getArguments()[0];
          return mockData;
      }
  }).when(mockConnection).write(any(byte[].
  
  when(mockConnection.read()).thenReturn(mockData);
  </code></pre>
  
  <p>I have real connection, that tested by callback write/read functions and it works fine. Then I want write unit test in case I haven't access to real connection. In this case I create <code>mockConnection</code> and stub <code>write()</code> (try save passed arg in <code>mockData</code> field) and <code>read()</code> (return earlier saved in write method arg) methods.</p>
  
  <p>What am I doing wrong?</p>