How to mock AmazonS3 getObject method using mockito

Viewed 426

I'm trying to mock AmazonS3 getObject method in Java using Mockito. But mocking is not working properly. It will still retrieve the file from S3. Could someone please help me in resolving this problem?

            AmazonS3 s3client = AmazonS3ClientBuilder
                    .standard()
                    .withRegion(Regions.US_EAST_1)
                    .build();
            S3Object object = s3client.getObject(new GetObjectRequest(bucketName, keyName));

            if (object == null) {
                throw new Exception("Object returned from S3 is null");
            }
            HashMap<String, String> s3Map = new HashMap<>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));

Test.java

@BeforeEach
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        String property = "environment=dev";
        InputStream testInputStream = new StringInputStream(property);
        AmazonS3ClientBuilder amazonS3ClientBuilder = Mockito.mock(AmazonS3ClientBuilder.class);
        AmazonS3Client amazonS3Client = Mockito.mock(AmazonS3Client.class);
        Mockito.when(amazonS3ClientBuilder.build()).thenReturn(amazonS3Client);
        S3ObjectInputStream s3ObjectInputStream = Mockito.mock(S3ObjectInputStream.class);
        S3Object s3Object = new S3Object();
        s3Object.setObjectContent(testInputStream);
        Mockito.when(amazonS3Client.getObject(ArgumentMatchers.any())).thenReturn(s3Object);
    }
0 Answers
Related