Skip to content
Advertisement

Mockito returning same argument of ArrayList which is passed

I have a method which is used as :

 List<Integer> permittedUserIds= this.getAuthorizationManager()
                    .getPermittedUserIDs(Constants.Permissions.Target.COMMON_DATA, Constants.Permissions.Action.READ,
                            userIdList);

The method mocking followed is as :

Option 1 :

Mockito.when(spied.getPermittedUserIDs(Mockito.anyString(),Mockito.anyString(),Mockito.anyList())).thenAnswer(i -> i.getArguments()[2]);

This is not even working because i think only doReturn needs to be worked, thenAnswer will not work here.

Option 2:

Mockito.doReturn(AdditionalAnswers.returnsLastArg())
                    .when(spied)
                    .getPermittedUserIDs(Mockito.anyString(), Mockito.anyString(), 
                     Mockito.anyList()); 

Getting Runtime exception as :

ERROR! java.lang.RuntimeException: org.mockito.exceptions.misusing.WrongTypeOfReturnValue: ReturnsArgumentAt cannot be returned by getPermittedUserIDs() getPermittedUserIDs() should return List

If you’re unsure why you’re getting above error read on. Due to the nature of the syntax above problem might occur because:

  1. This exception might occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies –
    • with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

Please suggest how it needs to be mocked. The idea is to return same array list which is passed in as last argument.

Advertisement

Answer

Use doAnswer instead of doReturn.

Here is example:

public class AppTest {

    @Test
    void test() {
        Service service = Mockito.mock(Service.class);
        List<Integer> userIdList = Arrays.asList(3,4);

        Mockito.doAnswer(AdditionalAnswers.returnsLastArg())
                .when(service)
                .getPermittedUserIDs(Mockito.anyString(), Mockito.anyString(),
                        Mockito.anyList());

        List<Integer> permittedUserIds= service
                .getPermittedUserIDs("1", "2",
                        userIdList);

        Assertions.assertSame(userIdList,permittedUserIds);
    }

    public interface Service {
        List<Integer> getPermittedUserIDs(String a, String b, List<Integer> userIdList);
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement