backtrack
backtrack

Reputation: 8144

java mockito matcher InvalidUseOfMatchersException

I am using java spring boot and trying to write a mock for AWS s3 bucket in my unittest. Following is a code that cause some issue in when i execute the test

    @Mock 
    AmazonS3 s3client;

    when(s3client.getObject(new GetObjectRequest(Mockito.any(String.class),
                    and(Mockito.any(String.class),Mockito.endsWith(".txt"))
                ))).thenReturn(RawText);

            when(s3client.getObject(new GetObjectRequest(Mockito.any(String.class),
                    and(Mockito.any(String.class),Mockito.endsWith(".png"))
                ))).thenReturn(RawImage);

What i am trying to do is, I need to read png file and a text file from S3 bucket. based on the content type i am trying to return the object. When i execute the test i am getting

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 2 recorded:

Note RawImage and RawText are the S3Object i created. Can you help me in this and what went wrong in my code?

Upvotes: 1

Views: 438

Answers (1)

ernest_k
ernest_k

Reputation: 45319

Matchers are expected to be used as arguments to getObject in this case. So you may want to implement a custom matcher if your actual argument isn't a mock:

org.hamcrest.Matcher<GetObjectRequest> objectRequestMatcher = 
         new BaseMatcher<GetObjectRequest>() {

    @Override
    public void describeTo(Description arg0) {
    }

    @Override
    public boolean matches(Object arg0) {
        return ((GetObjectRequest) arg0).getName().endsWith("txt"); //just an example
    }
};

And then:

when(s3client.getObject(org.mockito.Matchers.argThat(objectRequestMatcher)))
    .thenReturn(RawText);

Upvotes: 1

Related Questions