user3452444
user3452444

Reputation: 23

Mock method return with one of parameters

Im tryng to mock the return value with one of parameters, in this way:

    when( myService.saveMyEntity( TENANT_ID, DEFAULT_USER, Mockito.any( MyEntity.class ) ) ).thenAnswer(
            new Answer<MyEntity>() {
                @Override
                public MyEntity answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    return (MyEntity) args[2];
                }
            } );

But I got the follow error:

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

Whats the problem? How is the correct? Im using mockito 1.9.5 Thanks in advance for any help.

Upvotes: 0

Views: 301

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213391

You've to either use matchers for all the arguments of saveMyEntity method, or for none. You've to change that to:

when(myService.saveMyEntity(eq(TENANT_ID), any(User.class), any(MyEntity.class))).thenAnswer(
        new Answer<MyEntity>() {
            @Override
            public MyEntity answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                return (MyEntity) args[2];
            }
        } );

Also, as noted from @JBNizet's comment, since you're returning the last argument from your answer, you can use AdditionalAnswers.returnsLastArg() factory method:

when(myService.saveMyEntity(eq(TENANT_ID), any(User.class), any(MyEntity.class))).thenAnswer(AdditionalAnswers.returnsLastArg());

Upvotes: 1

Related Questions