java-在单元测试中,运行实际代码而不是函数存根和模拟对象

这是一个非常简单的单元测试用例.

我在School课堂上有两种方法:

protected S3Object getAwsObject(AmazonS3Client client, String bucketName, String keyName) {
        GetObjectRequest objRequest =  new GetObjectRequest(bucketName, keyName);
        return client.getObject(objRequest);
}

上面的方法由下面显示的第二种方法调用:

public void doTask() {
   // get client
   AmazonS3Client client = getAwsS3Client();
   // invoke the 1st method
   S3Object s3Obj = getAwsObject(client, "my-bucket", "my-key");
   ...
}

我使用Mockito测试方法doTask(),我尝试模拟AmazonS3Client&存根函数getAwsObject():

@Test
public void testDoTask() {
   // partially mocked School instance
   School school = new School();
   School schoolSpy = Mockito.spy(school);
   // mock the client & 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();
}

运行测试时,出现以下错误:

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),...

看起来测试用例运行的是真正的代码client.getObject(objRequest)而不是使用getAwsObject(…)的存根,为什么?

解决方法:

如果无法成功完成模拟工作,则可以通过以下方式覆盖原始方法来解决问题:

// mock the client & s3 object
final AmazonS3Client mockedClient = Mockito.mock(AmazonS3Client.class);
final S3Object mockedS3Obj = Mockito.mock(S3Object.class);

School school = new School(){

  @Override
  protected S3Object getAwsObject(AmazonS3Client client, String bucketName, String keyName) {
    return mockedS3Obj;
  }

  @Override
  protected AmazonS3Client getAwsS3Client() {
    return mockedClient;
  }

};

// system under test
school.doTask();
上一篇:java-捕获参数传递给powermockito中的存根


下一篇:android-在JUnit4和Mockito中编写SQLiteOpenHelper测试用例