模拟在测试方法中创建的 return 值(这是一个对象)

Mock the return value (which is an object) created inside a test method

我已经在网上参考了 Mocking Objects Created Inside method Under test, How to mock objects created inside method? 和其他问题的答案,但无法理解为什么我的解决方案不起作用。 我的测试方法是:

private AmazonS3 s3client;    
public int getBucketFileCount(String bucketNameForJsons) {
    if (s3client.doesBucketExistV2(bucketNameForJsons)) {
        log.info("Bucket name is not available.");
        return 0;
    }
    ObjectListing listing = s3client.listObjects(bucketNameForJsons);
    List<S3ObjectSummary> objectListing = listing.getObjectSummaries();
    log.info("Counting s3client files");
    return objectListing.size();
}

我写的测试用例是:

@Mock
private AmazonS3 s3clientMock;
@Mock
private ObjectListing listingMock;
private final String SAMPLE_BUCKET = "SAMPLE_BUCKET";

@InjectMocks
private Accessor accessor;

@Test
public void testGetBucketFileCount() {
    s3clientMock = Mockito.mock(AmazonS3.class);
    listingMock = Mockito.mock(ObjectListing.class);
    //PowerMockito.when(s3clientMock.listObjects(anyString())).thenReturn(listingMock);
 //PowerMockito.doReturn(listingMock).when(s3clientMock).listObjects(anyString());
    //PowerMockito.when(s3clientMock.listObjects(Matchers.any(String.class))).thenReturn(listingMock);
    List<S3ObjectSummary> objectListing = new ArrayList<>();
    S3ObjectSummary objectSummary1 = Mockito.mock(S3ObjectSummary.class);
    S3ObjectSummary objectSummary2 = Mockito.mock(S3ObjectSummary.class);
    objectListing.add(objectSummary1);
    objectListing.add(objectSummary2);
    Mockito.doReturn(objectListing).when(listingMock).getObjectSummaries();
    int actualSize = accessor.getBucketFileCount(SAMPLE_BUCKET);
    //Assert.assertNotEquals(actualSize, EXPECTED_SIZE);
}

我尝试通过以下方式模拟 ObjectListing listing = s3client.listObjects(bucketNameForJsons);

然而,我得到的 ObjectListing listing = s3client.listObjects(bucketNameForJsons) 的值仍然为空。

如何让它获取 listingMock 值?

谢谢。

首先,你把事情搞得太复杂了,因为你已经在使用注解了:

@Mock
private AmazonS3 s3clientMock;

那你应该坚持。含义:要么使用@RunWith or Mockito.initMocks。但是你绝对不应该s3clientMock = Mockito.mock(AmazonS3.class);。 (直接不疼,但在这里做会出现奇怪的效果,换个方法做就不同了)

那么:你根本不需要在这里使用PowerMock(ito)。您有两个模拟,并且您希望对每个模拟进行控制和方法调用。

很简单:

when(s3clientMock.listObjects(any())).thenReturn(listingMock);
when(listingMock.getObjectSummaries()).thenReturn(someList);

应该可以。 someList 将是 List<S3ObjectSummary>.

然后你可以去:

assertThat(accessor.getBucketFileCount(SAMPLE_BUCKET), is(someList.size())

例如