0

I need to mock the amazonS3.getObject(GetObjectRequest, File) from com.amazonaws.services.s3 library, to test my own method that gets a file from it.

I need one test where the requested object is found and everything is ok, and one where file is not found in S3 bucked, and thenReturn would return null.

So the simple case is something like:

ObjectMetadata objectMetadata = new ObjectMetadata();

Mockito.lenient().when(amazonS3.getObject(any(GetObjectRequest.class), any(File.class))).thenReturn(objectMetadata);

How do I duplicate and modify this to allow different return as per the object input?

In the function itself, this is what is being fed as GetObjectRequest:

GetObjectRequest getObjectRequest = new GetObjectRequest(this.getBucketName(), objectKey);

So we neeed to change any(GetObjectRequest.class) to something that will distinguish an object where objectKey (string) is "X", of another call where the objectKey is "Y", in which case I want to return null to fully test my function.

I hope the question is clear?

1 Answer 1

1

I hope i understand that correctly.

If it is helping, you can try

when(amazonS3.getObject(any(GetObjectRequest.class),any(File.class)))
.thenReturn(objectMetadata)
.thenReturn(null); 

first call should return your objectMetadata, second a null.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm, that will work only if used within the same test method as otherwise order of execution of test methods cannot be guaranteed. I was hoping to do it using two separate test methods, hence my question how to set different returns for each invocation with a different parameter value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.