如何在 Mockito 中单元测试 Lambda 函数?

How to unit Test Lambda functions in Mockito?

我有一个 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 是我用来创建相应模拟的实用函数。

Class 也模拟:

    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.

我是不是在 mocking 的时候遗漏了什么?

我会把 lambda 的内容移到一个单独的方法中,可以直接测试:

public void someMethod() {
   s3Event.getRecords().forEach(this::parse);
}

void parse(...) {
   ...
}

这也会提高可读性,因为多于一行的 lambda 比具有不言自明名称的方法参考更难阅读。