|
| 1 | +package com.baeldung.s3; |
| 2 | + |
| 3 | +import com.amazonaws.event.ProgressListener; |
| 4 | +import com.amazonaws.services.s3.AmazonS3; |
| 5 | +import com.amazonaws.services.s3.model.PutObjectRequest; |
| 6 | +import com.amazonaws.services.s3.model.PutObjectResult; |
| 7 | +import com.amazonaws.services.s3.transfer.TransferManager; |
| 8 | +import com.amazonaws.services.s3.transfer.TransferManagerBuilder; |
| 9 | +import com.amazonaws.services.s3.transfer.Upload; |
| 10 | +import org.junit.Before; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +import java.io.File; |
| 14 | +import java.util.concurrent.Executors; |
| 15 | + |
| 16 | +import static org.assertj.core.api.Assertions.assertThat; |
| 17 | +import static org.mockito.ArgumentMatchers.any; |
| 18 | +import static org.mockito.ArgumentMatchers.anyString; |
| 19 | +import static org.mockito.Mockito.mock; |
| 20 | +import static org.mockito.Mockito.verify; |
| 21 | +import static org.mockito.Mockito.when; |
| 22 | + |
| 23 | +public class MultipartUploadTest { |
| 24 | + |
| 25 | + private static final String BUCKET_NAME = "bucket_name"; |
| 26 | + private static final String KEY_NAME = "picture.jpg"; |
| 27 | + |
| 28 | + private AmazonS3 amazonS3; |
| 29 | + private TransferManager tm; |
| 30 | + private ProgressListener progressListener; |
| 31 | + |
| 32 | + @Before |
| 33 | + public void setup() { |
| 34 | + amazonS3 = mock(AmazonS3.class); |
| 35 | + tm = TransferManagerBuilder |
| 36 | + .standard() |
| 37 | + .withS3Client(amazonS3) |
| 38 | + .withMultipartUploadThreshold((long) (5 * 1024 * 1025)) |
| 39 | + .withExecutorFactory(() -> Executors.newFixedThreadPool(5)) |
| 40 | + .build(); |
| 41 | + progressListener = |
| 42 | + progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred()); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void whenUploadingFileWithTransferManager_thenVerifyUploadRequested() { |
| 47 | + File file = mock(File.class); |
| 48 | + PutObjectResult s3Result = mock(PutObjectResult.class); |
| 49 | + |
| 50 | + when(amazonS3.putObject(anyString(), anyString(), (File) any())).thenReturn(s3Result); |
| 51 | + when(file.getName()).thenReturn(KEY_NAME); |
| 52 | + |
| 53 | + PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, KEY_NAME, file); |
| 54 | + request.setGeneralProgressListener(progressListener); |
| 55 | + |
| 56 | + Upload upload = tm.upload(request); |
| 57 | + |
| 58 | + assertThat(upload).isNotNull(); |
| 59 | + verify(amazonS3).putObject(request); |
| 60 | + } |
| 61 | +} |
0 commit comments