title: In unit test, real code is run instead of function stub & mocked object
body: <p>It is a very simple unit test case.</p>
  
  <p>I have two methods in class <code>School</code>:</p>
  
  <pre><code>protected S3Object getAwsObject(AmazonS3Client client, String bucketName, String keyName) {
          GetObjectRequest objRequest =  new GetObjectRequest(bucketName, keyName);
          return client.getObject(objRequest);
  }
  </code></pre>
  
  <p>Above method is invoked by the 2nd method showing below:</p>
  
  <pre><code>public void doTask() {
     // get client
     AmazonS3Client client = getAwsS3Client();
     // invoke the 1st method
     S3Object s3Obj = getAwsObject(client, "my-bucket", "my-key");
     ...
  }
  </code></pre>
  
  <p>I use <a href="http://mockito.org/" rel="nofollow">Mockito</a> to test the method <code>doTask()</code>, I tried to <strong>mock</strong> the <code>AmazonS3Client</code> &amp; <strong>stub</strong> function <code>getAwsObject()</code> :</p>
  
  <pre><code>@Test
  public void testDoTask() {
     // partially mocked School instance
     School school = new School();
     School schoolSpy = Mockito.spy(school);
     // mock the client &amp; s3 object
     AmazonS3Client mockedClient = Mockito.mock(AmazonS3Client.class);
  
     S3Object mockedS3Obj = Mockito.mock(S3Object.class);
  
     Mockito.doReturn(mockedClient)
         .when(schoolSpy).getAwsS3Client();
  
     // PROBLEM HERE: I stub function to return mocked S3Object, but real code is run
     Mockito.doReturn(mockedS3Obj)
            .when(schoolSpy).getAwsObject(mockedClient, "my-bucket", "my-key");
  
     // system under test
     schoolSpy.doTask();
  }
  </code></pre>
  
  <p>When run the test, I got the following error:</p>
  
  <pre><code>com.amazonaws.services.s3.model.AmazonS3Exception: 
  The AWS Access Key Id you provided does not exist in our records. 
  
  (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: 6B973FC095C28524),...
  </code></pre>
  
  <p>Looks like the test case run the real code <code>client.getObject(objRequest)</code> instead of using the stub of <code>getAwsObject(...)</code> , WHY?</p>