【发布时间】:2021-11-03 21:20:23
【问题描述】:
我有一个 lambda 处理程序,它会在每次 S3Event 时触发。
s3Event.getRecords().forEach(record->{
final String bucket = record.getS3().getBucket().getName();
final String object = record.getS3().getObject().getKey();
S3Object s3Object = amazonS3.getObject(bucket, object);
... More parsing logic
所以为了测试这个功能,我创建了 Mock S3Event 构建器,它将为我构建一个模拟 S3Event。还有
S3Event s3Event = buildS3Event(S3_BUCKET_NAME, S3_FILE_NAME);
List<S3EventNotification.S3EventNotificationRecord> mockRecords = s3Event.getRecords();
S3EventNotification.S3EventNotificationRecord mockFirstRecord = s3Event.getRecords().get(0);
S3EventNotification.S3Entity mockS3Entity = mockFirstRecord.getS3();
S3EventNotification.S3BucketEntity mockS3BucketEntity = mockS3Entity.getBucket();
S3EventNotification.S3ObjectEntity mockS3ObjectEntity = mockS3Entity.getObject();
String bucketName = mockS3BucketEntity.getName();
String keyName = mockS3ObjectEntity.getKey();
BuildS3Event、getMockS3Bocket 是我用来创建相应模拟的实用函数。
类模拟也是如此:
s3Client = Mockito.mock(AmazonS3.class);
s3Object = Mockito.mock(S3Object.class);
s3EventMock = Mockito.mock(S3Event.class);
notificationRecord = Mockito.mock(S3EventNotification.S3EventNotificationRecord.class);
notificationRecords = Mockito.mock(List.class);
s3Entity = Mockito.mock(S3EventNotification.S3Entity.class);
s3BucketEntity = Mockito.mock(S3EventNotification.S3BucketEntity.class);
s3ObjectEntity = Mockito.mock(S3EventNotification.S3ObjectEntity.class);
when(s3EventMock.getRecords()).thenReturn(mockRecords);
handler.handle(s3Event, null) <--- calling the handler
verify(s3EventMock, times(1)).getRecords(); // seems to work
verify(notificationRecords, times(1)).get(0); // fails with wanted but not invoked error.
我在嘲笑时错过了什么吗?
【问题讨论】:
标签: java unit-testing junit mockito